﻿using System;
using System.Collections.Generic;
using System.Data;
using System.ServiceModel;
using System.Xaml;
using System.Activities.XamlIntegration;
using System.Activities;
//using ESOL.Services.DataContracts;
using System.IO;
using System.Threading;

using Suzsoft.Smart.Data;
using BPM.Foundation.PWService;
using BPM.Base.Tools;
using ESOL.Common;
using ESOL.Common.Entity;
using ESOL.Business.Sales;
using ESOL.Business.Mst;
using ESOL.Business.Bpt;
using ESOL.Business.Bom;
using ESOL.Business.Prod;

namespace ESOL.Services
{
    public class BptService : IBptService
    {
        public bool TestConnect()
        {
            return true;
        }

        public BptAppEntity GetBptAppByKey(string bptAppId)
        {
            try
            {
                if (string.IsNullOrEmpty(bptAppId))
                    return null;
                return BptAppBs.GetBptApp(new BptAppEntity { Id = bptAppId });
            }
            catch (Exception ex)
            {
                throw new FaultException<ProcessExecutionFault>
                    (new ProcessExecutionFault(), ex.Message);
            }
        }

        public int? AddBptMaintainApp(BptMaintainApp bptMaintainApp)
        {
            BptAppEntity bptApp = new BptAppEntity();
            if (bptMaintainApp.Id != null)
            {
                bptApp.Id = bptMaintainApp.Id;
            }
            bptApp.CreatedDate = DateTime.Now;
            if (bptMaintainApp.CreatedBy == null)
                return 1;
            else bptApp.CreatedBy = bptMaintainApp.CreatedBy;
            bptApp.UpdatedDate = DateTime.Now;
            if (bptMaintainApp.UpdatedBy == null)
                return 2;
            else bptApp.UpdatedBy = bptMaintainApp.UpdatedBy;
            if (bptMaintainApp.AppType != null)
            {
                bptApp.AppType = bptMaintainApp.AppType;
            }
            string code = MstCodeRuleBs.GetCurrentOrderCode("BptApplicationCode");
            if (code != null)
            {
                bptApp.AppCode = code;
            }
            if (bptMaintainApp.RequiredDate != null)
            {
                bptApp.RequiredDate = bptMaintainApp.RequiredDate;
            }
            else
            {
                return 3;
            }
            if (bptMaintainApp.SAppId != null)
            {
                bptApp.SalesAppId = bptMaintainApp.SAppId;
            }
            if (bptMaintainApp.SAppItemId != null)
            {
                bptApp.SalesAppItemId = bptMaintainApp.SAppItemId;
            }
            if (bptMaintainApp.AssignBy != null)
            {
                bptApp.AssignUser = bptMaintainApp.AssignBy;
            }
            if (bptMaintainApp.Description != null)
            {
                bptApp.Description = bptMaintainApp.Description;
            }
            if (bptMaintainApp.FinshedDate != null)
            {
                bptApp.FinishedDate = bptMaintainApp.FinshedDate;
            }
            if (bptMaintainApp.Remark != null)
            {
                bptApp.Remark = bptMaintainApp.Remark;
            }
            bptApp.Status = WfStatus.WFS10.ToString();
            if (BptAppBs.InsertBptApp(bptApp))
                return null;
            else return -1;
        }

        public int? UpdateBptMaintainApp(BptMaintainApp bptMaintainApp)
        {
            BptAppEntity bptApp = BptAppBs.GetBptApp(new BptAppEntity { Id = bptMaintainApp.Id });
            if (bptApp == null)
                return 1;
            bptApp.UpdatedDate = DateTime.Now;
            if (bptMaintainApp.UpdatedBy == null)
                return 2;
            else bptApp.UpdatedBy = bptMaintainApp.UpdatedBy;
            if (bptMaintainApp.AppType != null)
            {
                bptApp.AppType = bptMaintainApp.AppType;
            }
            if (bptMaintainApp.RequiredDate != null)
            {
                bptApp.RequiredDate = bptMaintainApp.RequiredDate;
            }
            else
            {
                return 3;
            }
            if (bptMaintainApp.SAppId != null)
            {
                bptApp.SalesAppId = bptMaintainApp.SAppId;
            }
            if (bptMaintainApp.SAppItemId != null)
            {
                bptApp.SalesAppItemId = bptMaintainApp.SAppItemId;
            }
            if (bptMaintainApp.AssignBy != null)
            {
                bptApp.AssignUser = bptMaintainApp.AssignBy;
            }
            if (bptMaintainApp.Description != null)
            {
                bptApp.Description = bptMaintainApp.Description;
            }
            if (bptMaintainApp.FinshedDate != null)
            {
                bptApp.FinishedDate = bptMaintainApp.FinshedDate;
            }
            if (bptMaintainApp.Remark != null)
            {
                bptApp.Remark = bptMaintainApp.Remark;
            }
            if (bptMaintainApp.Status != null)
            {
                bptApp.Status = bptMaintainApp.Status;
            }
            if (BptAppBs.UpdateBptApp(bptApp))
                return null;
            else return -1;
        }

        public DataSet GetBptAppByCondition(BptQueryCondition queryCondition)
        {
            try
            {
                int pageIndex = 1;
                int pageCount = 50;
                if (queryCondition.txtPageIndex != 0)
                    pageIndex = queryCondition.txtPageIndex;
                if (queryCondition.txtPageSize != 0)
                    pageCount = queryCondition.txtPageSize;
                string condition = "";
                if (!string.IsNullOrEmpty(queryCondition.txtSalesAppNo))
                {
                    condition += " AND SA.SALES_APP_NO LIKE '%" + queryCondition.txtSalesAppNo + "%'";
                }
                if (!string.IsNullOrEmpty(queryCondition.txtBptAppNo))
                {
                    condition += " AND BA.APP_CODE LIKE '%" + queryCondition.txtBptAppNo + "%'";
                }
                if (queryCondition.txtRequiredDateFrom != null && queryCondition.txtRequiredDateFrom != new DateTime(1, 1, 1))
                {
                    condition += " AND BA.REQUIRED_DATE >='" + queryCondition.txtRequiredDateFrom.ToString() + "'";
                }
                if (queryCondition.txtRequiredDateTo != null && queryCondition.txtRequiredDateTo != new DateTime(1, 1, 1))
                {
                    condition += " AND BA.REQUIRED_DATE <='" + queryCondition.txtRequiredDateTo.ToString() + "'";
                }
                if (!string.IsNullOrEmpty(queryCondition.cmbType))
                {
                    condition += " AND BA.APP_TYPE = '" + queryCondition.cmbType + "'";
                }
                if (!string.IsNullOrEmpty(queryCondition.cmbStatus))
                {
                    condition += " AND BA.STATUS = '" + queryCondition.cmbStatus + "'";
                }
                return BptAppBs.GetAllByCondition(pageIndex, pageCount, condition);
            }
            catch (Exception ex)
            {
                throw new FaultException<ProcessExecutionFault>
                    (new ProcessExecutionFault(), ex.Message);
            }
        }

        public BptTaskEntity GetBptTaskByKey(string bptTaskId)
        {
            try
            {
                if (string.IsNullOrEmpty(bptTaskId))
                    return null;
                return BptTaskBs.GetBptTask(new BptTaskEntity { Id = bptTaskId });
            }
            catch (Exception ex)
            {
                throw new FaultException<ProcessExecutionFault>
                    (new ProcessExecutionFault(), ex.Message);
            }
        }

        public DataSet GetBptTaskByCondition(int pageIndex, int pageCount, string condition)
        {
            try
            {
                return BptTaskBs.GetBptTaskByCondition(pageIndex, pageCount, condition);
            }
            catch (Exception ex)
            {
                throw new FaultException<ProcessExecutionFault>
                    (new ProcessExecutionFault(), ex.Message);
            }
        }

        public bool AddBptApp(BptAppEntity bptApp)
        {
            try
            {
                bptApp.CreatedDate = DateTime.Now;
                bptApp.UpdatedDate = DateTime.Now;
                return BptAppBs.InsertBptApp(bptApp);
            }
            catch (Exception ex)
            {
                throw new FaultException<ProcessExecutionFault>
                    (new ProcessExecutionFault(), ex.Message);
            }
        }


        public bool UpdateBptApp(BptAppEntity bptApp)
        {
            try
            {
                return BptAppBs.UpdateBptApp(bptApp);
            }
            catch (Exception ex)
            {
                throw new FaultException<ProcessExecutionFault>
                    (new ProcessExecutionFault(), ex.Message);
            }
        }

        public bool DelBptApp(BptAppEntity bptApp)
        {
            try
            {
                return BptAppBs.DeleteBptApp(bptApp);
            }
            catch (Exception ex)
            {
                throw new FaultException<ProcessExecutionFault>
                    (new ProcessExecutionFault(), ex.Message);
            }
        }

        ////启动工作流，首节点提交
        public bool CreateBptAppWf(BptAppEntity bptApp)
        {
            return false;
            //try
            //{
            //    SysTableEntity sysTable = SysTableBs.GetSysTableByTabName(bptApp.TableSchema.TableName);
            //    SysWfEntity sysWf = SysWfBs.GetSysWf(new SysWfEntity { Id = sysTable.WfId });
            //    var settings = new XamlXmlReaderSettings() { LocalAssembly = typeof(DocActivity).Assembly };
            //    var reader = new XamlXmlReader(sysWf.Url, settings);
            //    Activity workflow = ActivityXamlServices.Load(reader);
            //    var instance = new WorkflowApplication(workflow);
            //    instance.Run();
            //    Thread.Sleep(500);
            //    //初始化工作流实例存入缓存
            //    if (Cache.WfAppCaches == null)
            //        Cache.WfAppCaches = new List<WfAppCache>();
            //    Cache.WfAppCaches.Add(new WfAppCache { WfInstanceId = instance.Id.ToString(), wfApp = instance });
            //    //初始化事务类存入缓存
            //    DataAccessBroker broker = DataAccessFactory.Instance();
            //    if (Cache.BrokerCaches == null)
            //        Cache.BrokerCaches = new List<BrokerCache>();
            //    Cache.BrokerCaches.Add(new BrokerCache { WfInstanceId = instance.Id.ToString(), Broker = broker });

            //    var firstnd = SysWfNdBs.GetWfFirstNd(sysWf.Id);
            //    Dictionary<string, object> dict = new Dictionary<string, object>();
            //    dict.Add("RowId", bptApp.Id);
            //    dict.Add("WorkflowId", sysWf.Id);
            //    dict.Add("UserId", bptApp.CreatedBy);
            //    var resumeResult = instance.ResumeBookmark(firstnd.Bookmark, dict);
            //    Thread.Sleep(500);
            //    if (resumeResult.ToString().Equals("Success"))
            //    {
            //        var brokerCache = Cache.BrokerCaches.Find(a => a.WfInstanceId == instance.Id.ToString());
            //        if (brokerCache != null)
            //        {
            //            bptApp.Status = "WF20";
            //            DataAccess.Update(bptApp, brokerCache.Broker);
            //            brokerCache.Broker.Commit();
            //            Cache.BrokerCaches.Remove(brokerCache);
            //            brokerCache.Broker.Dispose();
            //            return true;
            //        }
            //    }
            //    return false;
            //}
            //catch (Exception ex)
            //{
            //    return false;
            //}
        }

        //public SysWfProcEntity SubmitBptAddWf(BptApplicationEntity bptApp, string userId, int result, string remark)
        //{
        //    try
        //    {
        //        return null;
        //        //return Common.WfApprove(bptApp.Id, userId, result, remark);
        //    }
        //    catch (Exception ex)
        //    {
        //        throw new FaultException<ProcessExecutionFault>
        //            (new ProcessExecutionFault(), ex.Message);
        //    }
        //}


        public bool UpdateBptTask(BptTaskEntity bptTask)
        {
            try
            {
                bptTask.UpdatedDate = DateTime.Now;
                return BptTaskBs.UpdateBptTask(bptTask);
            }
            catch (Exception ex)
            {
                throw new FaultException<ProcessExecutionFault>
                    (new ProcessExecutionFault(), ex.Message);
            }

        }

        public int? UpdateBptMaintainTask(BptMaintainTask bptMaintainTask)
        {
            try
            {
                if (bptMaintainTask == null)
                    return 1;
                if (string.IsNullOrEmpty(bptMaintainTask.Id))
                    return 2;
                BptTaskEntity bptTask = BptTaskBs.GetBptTask(new BptTaskEntity { Id = bptMaintainTask.Id });
                if (bptTask == null)
                    return 3;
                bptTask.UpdatedBy = bptMaintainTask.UpdatedBy;
                bptTask.UpdatedDate = DateTime.Now;
                bptTask.Status = bptMaintainTask.Status;

                if (BptTaskBs.UpdateBptTask(bptTask))
                    return null;
                else return -1;
            }
            catch (Exception ex)
            {
                throw new FaultException<ProcessExecutionFault>
                    (new ProcessExecutionFault(), ex.Message);
            }

        }


        //public BptTaskEntity ApproveBptApp(string loginPersonId, BptApplicationEntity bptApp, DataSet bptAppItems)
        //{
        //    try
        //    {
        //        bptApp.ApprovedBy = loginPersonId;
        //        return BptApplicationBs.ApproveBptAppSimple(bptApp, bptAppItems);
        //    }
        //    catch (Exception ex)
        //    {
        //        throw new FaultException<ProcessExecutionFault>
        //            (new ProcessExecutionFault(), ex.Message);
        //    }
        //}

        //public DataSet GetBptAttByAppId(string appId)
        //{
        //    try
        //    {
        //        return BptApplicationAttachedBs.GetBptAttByAppId(appId);
        //    }
        //    catch (Exception ex)
        //    {
        //        throw new FaultException<ProcessExecutionFault>
        //            (new ProcessExecutionFault(), ex.Message);
        //    }
        //}

        //public bool SaveBptAtt(BptApplicationAttachedEntity bptAtt, string type)
        //{
        //    try
        //    {
        //        return BptApplicationAttachedBs.SaveBptAtt(bptAtt, type);
        //    }
        //    catch (Exception ex)
        //    {
        //        throw new FaultException<ProcessExecutionFault>
        //            (new ProcessExecutionFault(), ex.Message);
        //    }
        //}

        //public bool DelBptAtt(BptApplicationAttachedEntity bptAtt)
        //{
        //    try
        //    {
        //        return BptApplicationAttachedBs.DelBptAtt(bptAtt);
        //    }
        //    catch (Exception ex)
        //    {
        //        throw new FaultException<ProcessExecutionFault>
        //            (new ProcessExecutionFault(), ex.Message);
        //    }
        //}


        /// <summary>
        /// 技术制图任务工作流完成
        /// 技术申请状态：完成
        /// 同步销售申请明细表产品ID
        /// 同步上传图纸路径到产品表
        /// 生成生产计划
        /// </summary>
        /// <param name="bptMaintainTask"></param>
        /// <returns></returns>
        public ProdPlanOrderEntity BptTaskToProdPo(BptMaintainTask bptMaintainTask)
        {
            try
            {
                if (bptMaintainTask == null)
                    return null;
                BptTaskEntity bptTask = BptTaskBs.GetBptTask(new BptTaskEntity { Id = bptMaintainTask.Id });
                if (bptTask == null)
                    return null;
                bptTask.Status = bptMaintainTask.Status;
                bptTask.UpdatedDate = DateTime.Now;
                bptTask.FinishedDate = DateTime.Now;
                if (string.IsNullOrEmpty(bptTask.BptAppId))
                    return null;
                BptAppEntity bptApp = BptAppBs.GetBptApp(new BptAppEntity { Id = bptTask.BptAppId });
                if (bptApp == null)
                    return null;
                if (string.IsNullOrEmpty(bptApp.SalesAppItemId))
                    return null;
                SalesAppItemEntity salesAppItem = DataAccess.SelectSingle<SalesAppItemEntity>(new SalesAppItemEntity { Id = bptApp.SalesAppItemId });
                if (salesAppItem == null)
                    return null;

                if (string.IsNullOrEmpty(bptTask.BlueprintId))
                    return null;
                BptBlueprintEntity bptBp = BptBlueprintBs.GetBptBlueprint(new BptBlueprintEntity { BlueprintId = bptTask.BlueprintId });
                if (bptBp.ProductId == null)
                    return null;
                salesAppItem.ProductId = bptBp.ProductId;

                var bps = BptBlueprintBs.GetBptBlueprintAllList(new BptBlueprintEntity { BptTaskId = bptMaintainTask.Id });
                if (bps == null)
                    return null;
                var prodcuts = new List<MstProductEntity>();
                foreach (var bp in bps)
                {
                    var product = MstProductBs.GetMstProduct(new MstProductEntity { ProductId = bp.ProductId });
                    if (product != null)
                    {
                        product.BlueprintPath = bp.FileName;
                        prodcuts.Add(product);
                    }
                    else
                    {
                        return null;
                    }
                }

                ProdPlanOrderEntity prodPo = new ProdPlanOrderEntity();
                prodPo.Id = Guid.NewGuid().ToString();
                prodPo.CreatedBy = bptMaintainTask.UpdatedBy;
                prodPo.CreatedDate = DateTime.Now;
                prodPo.UpdatedBy = bptMaintainTask.UpdatedBy;
                prodPo.UpdatedDate = DateTime.Now;
                string prodPoCode = MstCodeRuleBs.GetCurrentOrderCode("ProductPlanOrder");
                if (string.IsNullOrEmpty(prodPoCode))
                    return null;
                prodPo.PoNo = prodPoCode;
                prodPo.SappItemId = salesAppItem.Id;
                prodPo.ProductId = bptBp.ProductId;
                prodPo.Qty = salesAppItem.Qty;
                prodPo.DeliveryDate = salesAppItem.ReqDeliveryDate;
                prodPo.Status = Common.WfStatus.WFS10.ToString();
                prodPo.BlueprintId = bptBp.BlueprintId;
                prodPo.ContractModel = salesAppItem.CustomerModel;
                if (BptTaskBs.ApproveTask(bptTask, salesAppItem, prodcuts, prodPo))
                    return prodPo;
                else return null;
            }
            catch
            {
                return null;
            }
        }

        public BptTaskEntity BptAppToTask(BptMaintainApp bptMaintainApp)
        {
            BptAppEntity bptApp = BptAppBs.GetBptApp(new BptAppEntity { Id = bptMaintainApp.Id });
            if (bptApp == null)
                return null;
            bptApp.Status = Common.WfStatus.WFS20.ToString();
            if (!BptAppBs.UpdateBptApp(bptApp))
                return null;
            BptTaskEntity bptTask = new BptTaskEntity();
            bptTask.Id = Guid.NewGuid().ToString();
            bptTask.BptAppId = bptApp.Id;
            bptTask.IsActive = 1;
            bptTask.CreatedBy = bptApp.UpdatedBy;
            bptTask.CreatedDate = DateTime.Now;
            bptTask.UpdatedBy = bptApp.UpdatedBy;
            bptTask.UpdatedDate = DateTime.Now;
            string code = MstCodeRuleBs.GetCurrentOrderCode("BptTaskCode");
            if (code == null)
                return null;
            bptTask.TaskCode = code;
            bptTask.AssignUser = bptMaintainApp.AssignBy;
            bptTask.RequiredDate = bptApp.RequiredDate;
            bptTask.Status = Common.WfStatus.WFS20.ToString();
            if (BptTaskBs.InsertBptTask(bptTask))
                return bptTask;
            else return null;
        }

        public BptMaintainApp GetBptMaintainAppByKey(string bptAppId)
        {
            try
            {
                BptAppEntity bptApp = BptAppBs.GetBptApp(new BptAppEntity { Id = bptAppId });
                if (bptApp == null)
                    return null;
                BptMaintainApp bptMaintainApp = new BptMaintainApp();
                bptMaintainApp.Id = bptApp.Id;
                bptMaintainApp.CreatedBy = bptApp.CreatedBy;
                string connectionString = MyConfig.getConnection("myconstring");
                PowerService ps = new PowerService(new BPM.Foundation.PWDB.PWDBDataContext(connectionString));
                var createdUser = ps.getUser(null, bptApp.CreatedBy);
                if (createdUser != null)
                    bptMaintainApp.CreatedUser = createdUser.firstName;
                bptMaintainApp.CreatedDate = bptApp.CreatedDate;
                bptMaintainApp.UpdatedBy = bptApp.UpdatedBy;
                var updatedUser = ps.getUser(null, bptApp.UpdatedBy);
                if (updatedUser != null)
                    bptMaintainApp.UpdatedUser = updatedUser.firstName;
                bptMaintainApp.UpdatedDate = bptApp.UpdatedDate;
                if (bptApp.SalesAppId != null)
                {
                    bptMaintainApp.SAppId = bptApp.SalesAppId;
                    var salesApp = DataAccess.SelectSingle<SalesAppEntity>(new SalesAppEntity { Id = bptApp.SalesAppId });
                    if (salesApp.AppNo != null)
                        bptMaintainApp.SAppOrderNo = salesApp.AppNo;
                }
                if (bptApp.SalesAppItemId != null)
                {
                    bptMaintainApp.SAppItemId = bptApp.SalesAppItemId;
                }
                if (bptApp.AppType != null)
                {
                    bptMaintainApp.AppType = bptApp.AppType;
                }
                if (bptApp.AppCode != null)
                {
                    bptMaintainApp.AppCode = bptApp.AppCode;
                }
                if (bptApp.RequiredDate != null)
                {
                    bptMaintainApp.RequiredDate = bptApp.RequiredDate;
                }
                if (bptApp.AssignUser != null)
                {
                    bptMaintainApp.AssignBy = bptApp.AssignUser;
                    var assignUser = ps.getUser(null, bptApp.AssignUser);
                    if (assignUser != null)
                        bptMaintainApp.AssignUser = assignUser.firstName;
                }
                if (bptApp.Description != null)
                {
                    bptMaintainApp.Description = bptApp.Description;
                }
                if (bptApp.Remark != null)
                {
                    bptMaintainApp.Remark = bptApp.Remark;
                }
                if (bptApp.FinishedDate != null)
                {
                    bptMaintainApp.FinshedDate = bptApp.FinishedDate;
                }
                if (bptApp.Material != null)
                {
                    bptMaintainApp.Material = bptApp.Material;
                }
                if (bptApp.ContractModel != null)
                {
                    bptMaintainApp.ContractModel = bptApp.ContractModel;
                }
                if (bptApp.Status != null)
                {
                    bptMaintainApp.Status = bptApp.Status;
                }
                return bptMaintainApp;
            }
            catch (Exception ex)
            {
                throw new FaultException<ProcessExecutionFault>
                    (new ProcessExecutionFault(), ex.Message);
            }
        }

        public BptMaintainTask GetBptMaintainTaskByKey(string bptTaskId)
        {
            try
            {
                if (string.IsNullOrEmpty(bptTaskId))
                    return null;
                var bptTask = BptTaskBs.GetBptTask(new BptTaskEntity { Id = bptTaskId });
                if (bptTask == null)
                    return null;
                BptMaintainTask bptMaintainTask = new BptMaintainTask();
                bptMaintainTask.Id = bptTask.Id;
                string connectionString = MyConfig.getConnection("myconstring");
                PowerService ps = new PowerService(new BPM.Foundation.PWDB.PWDBDataContext(connectionString));
                var createdUser = ps.getUser(null, bptTask.CreatedBy);
                if (createdUser != null)
                {
                    bptMaintainTask.CreatedUser = createdUser.userNo;
                    bptMaintainTask.CreatedBy = bptTask.CreatedBy;
                }
                bptMaintainTask.CreatedDate = bptTask.CreatedDate;
                var updatedUser = ps.getUser(null, bptTask.UpdatedBy);
                if (updatedUser != null)
                {
                    bptMaintainTask.UpdatedUser = updatedUser.userNo;
                    bptMaintainTask.UpdatedBy = bptTask.UpdatedBy;
                }
                bptMaintainTask.UploadDate = bptTask.UpdatedDate;
                if (string.IsNullOrEmpty(bptTask.BptAppId))
                    return null;
                if (!bptTask.BptAppId.StartsWith("BPTC"))
                {
                    #region 制图申请
                    var bptApp = BptAppBs.GetBptApp(new BptAppEntity { Id = bptTask.BptAppId });
                    if (bptApp != null)
                    {
                        bptMaintainTask.BAppId = bptApp.Id;
                        bptMaintainTask.BAppCode = bptApp.AppCode;
                    }
                    else
                    {
                        return null;
                    }
                    var salesApp = DataAccess.SelectSingle<SalesAppEntity>(new SalesAppEntity { Id = bptApp.SalesAppId });
                    if (salesApp != null)
                    {
                        bptMaintainTask.SAppId = salesApp.Id;
                        bptMaintainTask.SAppCode = salesApp.AppNo;
                    }
                    if (!string.IsNullOrEmpty(salesApp.CustomerId))
                    {
                        var customer = DataAccess.SelectSingle<MstCustomerEntity>(new MstCustomerEntity { Id = salesApp.CustomerId });
                        if (customer != null)
                        {
                            bptMaintainTask.CustomerName = customer.CustomerName;
                        }
                    }
                    bptMaintainTask.TaskCode = bptTask.TaskCode;
                    var assignUser = ps.getUser(null, bptTask.AssignUser);
                    if (assignUser != null)
                    {
                        bptMaintainTask.AssignBy = assignUser.userNo;
                        bptMaintainTask.AssignUser = assignUser.firstName;
                    }
                    bptMaintainTask.BlueprintId = bptTask.BlueprintId;
                    if (!string.IsNullOrEmpty(bptTask.ProductId))
                    {
                        var product = MstProductBs.GetMstProduct(new MstProductEntity { ProductId = bptTask.ProductId });
                        if (product != null)
                        {
                            bptMaintainTask.ProductId = product.ProductId;
                            bptMaintainTask.ProductName = product.ProductName;
                        }
                    }
                    #endregion
                }
                else
                {
                    #region 制图变更申请
                    var bptApp = BptBlueprintChangesBs.GetBptBlueprintChanges(new BptBlueprintChangesEntity { ChangesCode = bptTask.BptAppId });
                    if (bptApp != null)
                    {
                        bptMaintainTask.BAppId = bptApp.Id;
                        bptMaintainTask.BAppCode = bptApp.ChangesCode;
                    }
                    else
                    {
                        return null;
                    }
                    var salesApp = DataAccess.SelectSingle<BptBlueprintChangesItemEntity>(new BptBlueprintChangesItemEntity { ChangesCode = bptApp.ChangesCode });
                    if (salesApp != null)
                    {
                        bptMaintainTask.SAppId = salesApp.Id;
                        bptMaintainTask.SAppCode = salesApp.ChangesCode;
                    }
                    //if (!string.IsNullOrEmpty(salesApp.CustomerId))
                    //{
                    //    var customer = DataAccess.SelectSingle<MstCustomerEntity>(new MstCustomerEntity { Id = salesApp.CustomerId });
                    //    if (customer != null)
                    //    {
                    //        bptMaintainTask.CustomerName = customer.CustomerName;
                    //    }
                    //}
                    bptMaintainTask.TaskCode = bptTask.TaskCode;
                    var assignUser = ps.getUser(null, bptTask.AssignUser);
                    if (assignUser != null)
                    {
                        bptMaintainTask.AssignBy = assignUser.userNo;
                        bptMaintainTask.AssignUser = assignUser.firstName;
                    }
                    bptMaintainTask.BlueprintId = bptTask.BlueprintId;
                    if (!string.IsNullOrEmpty(bptTask.ProductId))
                    {
                        var product = MstProductBs.GetMstProduct(new MstProductEntity { ProductId = bptTask.ProductId });
                        if (product != null)
                        {
                            bptMaintainTask.ProductId = product.ProductId;
                            bptMaintainTask.ProductName = product.ProductName;
                        }
                    }
                    else
                    {
                        var list = DataAccess.Select<BptBlueprintChangesItemEntity>(new BptBlueprintChangesItemEntity { ChangesCode = bptApp.ChangesCode });
                        if (list != null && list.Count > 0)
                        {
                            bptMaintainTask.ProductId = list[0].ProductId;
                            var product = MstProductBs.GetMstProduct(new MstProductEntity { ProductId = bptMaintainTask.ProductId });
                            if (product != null)
                            {
                                bptMaintainTask.ProductName = product.ProductName;
                            }

                        }
                    }
                    #endregion
                }
                bptMaintainTask.WorkingTime = bptTask.WorkingTime;
                bptMaintainTask.RequiredDate = bptTask.RequiredDate;
                bptMaintainTask.UploadDate = bptTask.UploadDate;
                bptMaintainTask.FinishedDate = bptTask.FinishedDate;
                bptMaintainTask.Remark = bptTask.Remark;
                bptMaintainTask.Status = bptTask.Status;

                return bptMaintainTask;
            }
            catch (Exception ex)
            {
                throw new FaultException<ProcessExecutionFault>
                    (new ProcessExecutionFault(), ex.Message);
            }
        }

        public FileUploadReturnMessage UploadBlueprint(FileUploadMessage request)
        {
            try
            {
                var sysStFile = DataAccess.SelectSingle<SysStFileEntity>(new SysStFileEntity { Type = "bpt_blueprint" });
                string uploadFolder = sysStFile.Path;
                string savaPath = @"Photo\";
                string dateString = DateTime.Now.ToShortDateString() + @"\";
                string fileName = request.RowID + "_" + request.Name;
                Stream sourceStream = request.FileData;
                FileStream targetStream = null;

                if (!sourceStream.CanRead)
                {
                    return null;
                }
                if (!savaPath.EndsWith("\\")) savaPath += "\\";
                uploadFolder = uploadFolder + savaPath + dateString;
                if (!Directory.Exists(uploadFolder))
                {
                    Directory.CreateDirectory(uploadFolder);
                }

                string filePath = Path.Combine(uploadFolder, fileName);
                using (targetStream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None))
                {
                    const int bufferLen = 4096;
                    byte[] buffer = new byte[bufferLen];
                    int count = 0;
                    while ((count = sourceStream.Read(buffer, 0, bufferLen)) > 0)
                    {
                        targetStream.Write(buffer, 0, count);
                    }
                    targetStream.Close();
                    sourceStream.Close();
                }
                FileUploadReturnMessage result = new FileUploadReturnMessage { FilePath = filePath };
                return result;
            }
            catch
            {
                return null;
            }
        }

        public FileDownloadReturnMessage DownloadBlueprint(FileDownloadMessage request)
        {
            if (!File.Exists(request.FilePath))
                return new FileDownloadReturnMessage { FileData = null };
            var file = Common.CommonFunctions.FileToByte(request.FilePath);
            if (file == null)
                return null;
            FileDownloadReturnMessage result = new FileDownloadReturnMessage { FileData = file };
            return result;
        }

        public BptMaintainTask SaveBptTask(string userNo, BptMaintainTask bptMaintainTask, List<BptBlueprintEntity> bpInfo)
        {
            try
            {
                if (bptMaintainTask == null || bpInfo == null)
                    return null;
                var bptTask = BptTaskBs.GetBptTask(new BptTaskEntity { Id = bptMaintainTask.Id });
                if (bptTask == null)
                    return null;

                List<BptBlueprintEntity> list = new List<BptBlueprintEntity>();
                string parentBpId = null;
                string parentProductId = null;
                for (int i = 0; i < bpInfo.Count; i++)
                {
                    string sProductCode = bpInfo[i].BlueprintCode.Trim();
                    if (string.IsNullOrEmpty(sProductCode))
                        return null;
                    var product = MstProductBs.GetMstProduct(new MstProductEntity { ProductCode = sProductCode });
                    if (product == null)
                        return null;
                    bpInfo[i].BlueprintId = Guid.NewGuid().ToString();
                    if (i == 0)
                    {
                        parentBpId = bpInfo[i].BlueprintId;
                        parentProductId = product.ProductId;
                        bpInfo[i].ParentId = null;
                    }
                    if (i > 0)
                    {
                        bpInfo[i].ParentId = parentBpId;
                    }
                    bpInfo[i].BptTaskId = bptMaintainTask.Id;
                    //entity.BlueprintCode = bpInfo[i]["BLUEPRINT_CODE"].ToString();
                    //entity.BlueprintName = bpInfo[i]["BLUEPRINT_NAME"].ToString();
                    //entity.BlueprintType = "";
                    bpInfo[i].CreatedDate = DateTime.Now;
                    bpInfo[i].CreatedBy = userNo;
                    bpInfo[i].UpdatedDate = DateTime.Now;
                    bpInfo[i].UpdatedBy = userNo;
                    //entity.FileName = bpInfo[i]["FILE_NAME"].ToString();
                    //entity.MaterialId = bpInfo[i]["MATERIAL"].ToString();
                    //entity.MaterialQty = Convert.ToDecimal(bpInfo[i]["MATERIAL_QTY"]);
                    bpInfo[i].ProductId = product.ProductId;
                    bpInfo[i].Remark = bpInfo[i]["REMARK"].ToString();
                    bpInfo[i].Sequence = Convert.ToDecimal(bpInfo[i]["SEQUENCE"]);
                    bpInfo[i].DeletefLag = 0;
                    //list.Add(entity);
                }

                bptTask.UpdatedBy = bptMaintainTask.UpdatedBy;
                bptTask.UpdatedDate = DateTime.Now;
                bptTask.UploadDate = DateTime.Now;
                bptTask.ProductId = parentProductId;
                bptTask.BlueprintId = parentBpId;
                bptTask.Remark = bptMaintainTask.Remark;

                if (BptTaskBs.SaveTask(bptTask, bpInfo))
                {
                    bptMaintainTask.BlueprintId = bptTask.BlueprintId;
                    bptMaintainTask.UploadDate = bptTask.UpdatedDate;
                    bptMaintainTask.Remark = bptTask.Remark;
                    return bptMaintainTask;
                }
                else
                {
                    return null;
                }
            }
            catch (Exception ex)
            {
                throw new FaultException<ProcessExecutionFault>
                    (new ProcessExecutionFault(), ex.Message);
            }
        }

        public BomMasterEntity BptTaskToBom(BptMaintainTask bptMaintainTask)
        {
            if (bptMaintainTask == null)
                return null;
            var bp = BptBlueprintBs.GetBptBlueprint(new BptBlueprintEntity { BlueprintId = bptMaintainTask.BlueprintId });
            if (bp == null)
                return null;
            List<BptBlueprintEntity> bps = new List<BptBlueprintEntity>();
            bps = BptBlueprintBs.getBptBpsByParentID(bptMaintainTask.BlueprintId);
            if (bps.Count > 0)
            {
                bps.Insert(0, bp);
            }
            var bomMaster = new BomMasterEntity();
            bomMaster.Id = Guid.NewGuid().ToString();
            bomMaster.CreatedBy = bptMaintainTask.UpdatedBy;
            bomMaster.CreatedDate = DateTime.Now;
            bomMaster.UpdatedBy = bptMaintainTask.UpdatedBy;
            bomMaster.UpdatedDate = DateTime.Now;
            bomMaster.IsActive = 1;
            bomMaster.Name = bps[0].BlueprintName;
            bomMaster.BlueprintId = bps[0].BlueprintId;
            bomMaster.ProductId = bps[0].ProductId;
            bomMaster.Description = "系统自动产生！";
            bomMaster.Ver = DateTime.Now.ToString("yyyyMMddHHmmss");
            bomMaster.Status = Common.WfStatus.WFS10.ToString();

            List<BomItemEntity> bomItems = new List<BomItemEntity>();
            bomItems.Add(new BomItemEntity
            {
                Id = Guid.NewGuid().ToString(),
                BomMasterId = bomMaster.Id,
                Version = DateTime.Now.ToString("yyyyMMddHHmmss"),
                ProductId = bomMaster.ProductId,
                BpId = bomMaster.BlueprintId,
                ItemType = "PDTYPE01",
                Seqence = 1,
                UnitDose = 1,
                Remark = "系统自动产生"
            });
            for (int i = 0; i < bps.Count; i++)
            {
                var bomItem = new BomItemEntity();
                bomItem.Id = Guid.NewGuid().ToString();
                bomItem.BomMasterId = bomMaster.Id;
                bomItem.ParentId = bomItems[0].Id;
                bomItem.Version = DateTime.Now.ToString("yyyyMMddHHmmss");
                bomItem.ProductId = bps[i].ProductId;
                bomItem.BpId = bps[i].BlueprintId;
                bomItem.Seqence = i + 2;
                bomItem.UnitDose = bps[i].MaterialQty;
                bomItem.Remark = "系统自动产生";
                bomItems.Add(bomItem);
            }
            if (ESOL.Business.Bom.BomMasterBs.AddBomMasterAndItem(bomMaster, bomItems))
                return bomMaster;
            else return null;
        }

        public BomMaintainTechnic AddBomTechnic(BomMaintainTechnic bomMaintainTechnic)
        {
            try
            {
                if (bomMaintainTechnic == null)
                    return null;
                if (string.IsNullOrEmpty(bomMaintainTechnic.Id))
                    return null;
                bomMaintainTechnic.CreatedDate = DateTime.Now;
                bomMaintainTechnic.UpdatedDate = DateTime.Now;
                string connectionString = MyConfig.getConnection("myconstring");
                PowerService ps = new PowerService(new BPM.Foundation.PWDB.PWDBDataContext(connectionString));
                var createdUser = ps.getUser(null, bomMaintainTechnic.CreatedBy);
                if (createdUser != null && !string.IsNullOrEmpty(createdUser.firstName))
                    bomMaintainTechnic.CreatedUser = createdUser.firstName;
                var updatedUser = ps.getUser(null, bomMaintainTechnic.UpdatedBy);
                if (updatedUser != null && !string.IsNullOrEmpty(updatedUser.firstName))
                    bomMaintainTechnic.UpdatedUser = updatedUser.firstName;
                BomTechnicEntity bomTechnic = new BomTechnicEntity
                {
                    Id = bomMaintainTechnic.Id,
                    CreatedBy = bomMaintainTechnic.CreatedBy,
                    CreatedDate = bomMaintainTechnic.CreatedDate,
                    UpdatedBy = bomMaintainTechnic.UpdatedBy,
                    UpdatedDate = bomMaintainTechnic.UpdatedDate,
                    IsActive = bomMaintainTechnic.IsActive,
                    ProductId = bomMaintainTechnic.ProductId,
                    ProductName = bomMaintainTechnic.ProductName,
                    ProductCode = bomMaintainTechnic.ProductCode,
                    Ver = bomMaintainTechnic.Ver,
                    Description = bomMaintainTechnic.Description,
                    Status = bomMaintainTechnic.Status,
                    Name = bomMaintainTechnic.Name
                };
                if (BomTechnicBs.InsertBomTechnic(bomTechnic))
                    return bomMaintainTechnic;
                else return null;
            }
            catch (Exception ex)
            {
                throw new FaultException<ProcessExecutionFault>
                    (new ProcessExecutionFault(), ex.Message);
            }
        }

        public BomMaintainTechnic UpdateBomTechnic(BomMaintainTechnic bomMaintainTechnic)
        {
            try
            {
                if (bomMaintainTechnic == null)
                    return null;
                if (string.IsNullOrEmpty(bomMaintainTechnic.Id))
                    return null;
                BomTechnicEntity bomTechnic = BomTechnicBs.GetBomTechnic(new BomTechnicEntity { Id = bomMaintainTechnic.Id });
                if (bomTechnic == null)
                    return null;
                bomMaintainTechnic.UpdatedDate = DateTime.Now;

                bomTechnic.UpdatedBy = bomMaintainTechnic.UpdatedBy;
                bomTechnic.UpdatedDate = bomMaintainTechnic.UpdatedDate;
                bomTechnic.IsActive = bomMaintainTechnic.IsActive;
                bomTechnic.ProductId = bomMaintainTechnic.ProductId;
                bomTechnic.ProductName = bomMaintainTechnic.ProductName;
                bomTechnic.ProductCode = bomMaintainTechnic.ProductCode;
                bomTechnic.Ver = bomMaintainTechnic.Ver;
                bomTechnic.Description = bomMaintainTechnic.Description;
                bomTechnic.Status = bomMaintainTechnic.Status;
                bomTechnic.Name = bomMaintainTechnic.Name;
                bool result = false;
                if (bomTechnic.IsActive == 1)
                    result = BomTechnicBs.UpdateAndActiveBomTechnic(bomTechnic);
                else
                    result = BomTechnicBs.UpdateBomTechnic(bomTechnic);
                if (result)
                    return bomMaintainTechnic;
                else return null;
            }
            catch (Exception ex)
            {
                throw new FaultException<ProcessExecutionFault>
                    (new ProcessExecutionFault(), ex.Message);
            }
        }

        public int? DelBomTechnic(BomMaintainTechnic bomMaintainTechnic)
        {
            try
            {
                if (bomMaintainTechnic == null)
                    return 1;
                if (string.IsNullOrEmpty(bomMaintainTechnic.Id))
                    return 2;
                BomTechnicEntity bomTechnic = BomTechnicBs.GetBomTechnic(new BomTechnicEntity { Id = bomMaintainTechnic.Id });
                if (bomTechnic == null)
                    return 3;
                if (BomTechnicBs.DeleteBomTechnic(bomTechnic))
                    return null;
                else return -1;
            }
            catch (Exception ex)
            {
                throw new FaultException<ProcessExecutionFault>
                    (new ProcessExecutionFault(), ex.Message);
            }
        }

        public BomMaintainTechnic GetBomTechnicByKey(string bomTechnicId)
        {
            try
            {
                if (string.IsNullOrEmpty(bomTechnicId))
                    return null;
                var bomT = BomTechnicBs.GetBomTechnic(new BomTechnicEntity { Id = bomTechnicId });
                if (bomT == null)
                    return null;
                string connectionString = MyConfig.getConnection("myconstring");
                PowerService ps = new PowerService(new BPM.Foundation.PWDB.PWDBDataContext(connectionString));
                var createdUser = ps.getUser(null, bomT.CreatedBy);
                var updatedUser = ps.getUser(null, bomT.UpdatedBy);
                var product = MstProductBs.GetMstProduct(new MstProductEntity { ProductId = bomT.ProductId });
                BomMaintainTechnic bomMT = new BomMaintainTechnic
                {
                    Id = bomT.Id,
                    CreatedBy = bomT.CreatedBy,
                    CreatedUser = (createdUser != null) ? createdUser.firstName : "",
                    CreatedDate = DateTime.Now,
                    UpdatedBy = bomT.UpdatedBy,
                    UpdatedUser = (updatedUser != null) ? updatedUser.firstName : "",
                    UpdatedDate = DateTime.Now,
                    IsActive = bomT.IsActive,
                    ProductId = bomT.ProductId,
                    ProductCode = product.ProductCode,
                    ProductName = product.ProductName,
                    Ver = bomT.Ver,
                    Description = bomT.Description,
                    Status = bomT.Status,
                    ParentId = bomT.ParentId,
                    LogicNo = bomT.LogicNo,
                    Name = bomT.Name
                };
                return bomMT;
            }
            catch (Exception ex)
            {
                throw new FaultException<ProcessExecutionFault>
                    (new ProcessExecutionFault(), ex.Message);
            }
        }

        public List<BomMaintainTechnic> GetBomTechnicAllListByCondition(BomQueryCondition queryCondition)
        {
            int pageIndex = 1;
            int pageCount = 50;
            string condition = "";
            if (queryCondition != null)
            {
                if (queryCondition.txtPageIndex != 0)
                    pageIndex = queryCondition.txtPageIndex;
                if (queryCondition.txtPageSize != 0)
                    pageCount = queryCondition.txtPageSize;

                if (!string.IsNullOrEmpty(queryCondition.ProductName))
                {
                    condition += " AND BT.PRODUCT_NAME LIKE '%" + queryCondition.ProductName + "%'";
                }
                if (!string.IsNullOrEmpty(queryCondition.ProductCode))
                {
                    condition += " AND BT.PRODUCT_CODE LIKE '%" + queryCondition.ProductCode + "%'";
                }
                if (!string.IsNullOrEmpty(queryCondition.Status))
                {
                    condition += " AND BT.STATUS = '" + queryCondition.Status + "'";
                }
                if (!string.IsNullOrEmpty(queryCondition.Ver))
                {
                    condition += " AND BT.VER = '" + queryCondition.Ver + "'";
                }

                if (!string.IsNullOrEmpty(queryCondition.ProductId))
                {
                    condition += " AND BT.PRODUCT_ID = '" + queryCondition.ProductId + "'";
                }
            }
            DataSet ds = BomTechnicBs.GetAllByCondition(pageIndex, pageCount, condition);
            if (ds.Tables[0].Rows.Count == 0)
                return null;
            var results = new List<BomMaintainTechnic>();
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                var result = new BomMaintainTechnic
                {
                    Id = dr["ID"].ToString(),
                    CreatedBy = dr["CREATED_BY"].ToString(),
                    CreatedUser = dr["CREATED_USER"].ToString(),
                    CreatedDate = (DateTime)dr["CREATED_DATE"],
                    UpdatedBy = dr["UPDATED_BY"].ToString(),
                    UpdatedUser = dr["UPDATED_USER"].ToString(),
                    UpdatedDate = (DateTime)dr["UPDATED_DATE"],
                    IsActive = string.IsNullOrEmpty(dr["IS_ACTIVE"].ToString()) ? 0 : (int)dr["IS_ACTIVE"],
                    ProductId = dr["PRODUCT_ID"].ToString(),
                    ProductCode = dr["PRODUCT_CODE"].ToString(),
                    ProductName = dr["PRODUCT_NAME"].ToString(),
                    Ver = dr["VER"].ToString(),
                    Description = dr["DESCRIPTION"].ToString(),
                    Status = dr["STATUS"].ToString(),
                    Name = dr["NAME"].ToString()
                };
                results.Add(result);
            }
            return results;
        }

        public DataSet GetBomTechnicAllDsByCondition(TechnicQueryCondition queryCondition)
        {
            int pageIndex = 1;
            int pageCount = 50;
            if (queryCondition.txtPageIndex != 0)
                pageIndex = queryCondition.txtPageIndex;
            if (queryCondition.txtPageSize != 0)
                pageCount = queryCondition.txtPageSize;
            string condition = "";
            if (!string.IsNullOrEmpty(queryCondition.ProductId))
            {
                condition += " AND BT.PRODUCT_ID like '%" + queryCondition.ProductId + "%'";
            }
            else if (!string.IsNullOrEmpty(queryCondition.ProductName))
            {
                condition += " AND bt.PRODUCT_NAME LIKE '%" + queryCondition.ProductName + "%'";
            }
            // condition += " AND BT.IS_ACTIVE = " + queryCondition.IsActive + "";
            if (!string.IsNullOrEmpty(queryCondition.Status))
            {
                condition += " AND BT.STATUS = '" + queryCondition.Status + "'";
            }
            if (!string.IsNullOrEmpty(queryCondition.Ver))
            {
                condition += " AND BT.VER = '" + queryCondition.Ver + "'";
            }
            if (!string.IsNullOrEmpty(queryCondition.Name))
                condition += " AND BT.Name  like '%" + queryCondition.Name + "%'";

            return BomTechnicBs.GetAllByCondition(pageIndex, pageCount, condition);
        }

        public BomMaintainTechnicItem AddBomTechnicItem(BomMaintainTechnicItem bomMaintainTechnicItem)
        {
            try
            {
                if (bomMaintainTechnicItem == null)
                    return null;
                if (string.IsNullOrEmpty(bomMaintainTechnicItem.Id))
                    return null;
                BomTechnicItemEntity bomTechnicItem = new BomTechnicItemEntity
                {
                    Id = bomMaintainTechnicItem.Id,
                    TechnicId = bomMaintainTechnicItem.TechnicId,
                    BomTechnicId = bomMaintainTechnicItem.BomTechnicId,
                    Sequence = bomMaintainTechnicItem.Sequence,
                    Description = bomMaintainTechnicItem.Description
                };
                if (BomTechnicItemBs.InsertBomTechnicItem(bomTechnicItem))
                    return bomMaintainTechnicItem;
                else return null;
            }
            catch (Exception ex)
            {
                throw new FaultException<ProcessExecutionFault>
                    (new ProcessExecutionFault(), ex.Message);
            }
        }

        public int? AddBomTechnicItems(List<BomMaintainTechnicItem> bomMaintainTechnicItems)
        {
            try
            {
                if (bomMaintainTechnicItems == null)
                    return 1;
                if (bomMaintainTechnicItems.Count == 0)
                    return 2;
                var bomTechnicItems = new List<BomTechnicItemEntity>();
                foreach (var mti in bomMaintainTechnicItems)
                {
                    BomTechnicItemEntity bomTechnicItem = new BomTechnicItemEntity
                    {
                        Id = mti.Id,
                        TechnicId = mti.TechnicId,
                        BomTechnicId = mti.BomTechnicId,
                        Sequence = mti.Sequence,
                        Description = mti.Description
                    };
                    bomTechnicItems.Add(bomTechnicItem);
                }
                if (BomTechnicItemBs.InsertBomTechnicItem(bomTechnicItems))
                    return null;
                else return -1;
            }
            catch (Exception ex)
            {
                throw new FaultException<ProcessExecutionFault>
                    (new ProcessExecutionFault(), ex.Message);
            }
        }

        public BomMaintainTechnicItem UpdateBomTechnicItem(BomMaintainTechnicItem bomMaintainTechnicItem)
        {
            try
            {
                if (bomMaintainTechnicItem == null)
                    return null;
                if (string.IsNullOrEmpty(bomMaintainTechnicItem.Id))
                    return null;
                var bomTechnicItem = BomTechnicItemBs.GetBomTechnicItem(new BomTechnicItemEntity { Id = bomMaintainTechnicItem.Id });
                if (bomTechnicItem == null)
                    return null;
                bomTechnicItem.BomTechnicId = bomMaintainTechnicItem.BomTechnicId;
                bomTechnicItem.TechnicId = bomMaintainTechnicItem.TechnicId;
                bomTechnicItem.Sequence = bomMaintainTechnicItem.Sequence;
                bomTechnicItem.Description = bomMaintainTechnicItem.Description;
                if (BomTechnicItemBs.UpdateBomTechnicItem(bomTechnicItem))
                    return bomMaintainTechnicItem;
                else return null;
            }
            catch (Exception ex)
            {
                throw new FaultException<ProcessExecutionFault>
                    (new ProcessExecutionFault(), ex.Message);
            }
        }

        public int? UpdateBomTechnicItems(List<BomMaintainTechnicItem> bomMaintainTechnicItems)
        {
            try
            {
                if (bomMaintainTechnicItems == null)
                    return null;
                if (bomMaintainTechnicItems.Count == 0)
                    return null;
                var tis = new List<BomTechnicItemEntity>();
                foreach (var mti in bomMaintainTechnicItems)
                {
                    var ti = BomTechnicItemBs.GetBomTechnicItem(new BomTechnicItemEntity { Id = mti.Id });
                    if (ti == null)
                        return null;
                    ti.BomTechnicId = mti.BomTechnicId;
                    ti.TechnicId = mti.TechnicId;
                    ti.Sequence = mti.Sequence;
                    ti.Description = mti.Description;
                    tis.Add(ti);
                }
                if (BomTechnicItemBs.UpdateBomTechnicItem(tis))
                    return null;
                else return -1;
            }
            catch (Exception ex)
            {
                throw new FaultException<ProcessExecutionFault>
                    (new ProcessExecutionFault(), ex.Message);
            }
        }

        public int? DelBomTechnicItem(BomMaintainTechnicItem bomMaintainTechnicItem)
        {
            try
            {
                if (bomMaintainTechnicItem == null)
                    return 1;
                if (string.IsNullOrEmpty(bomMaintainTechnicItem.Id))
                    return 2;
                var bomTechnicItem = BomTechnicItemBs.GetBomTechnicItem(new BomTechnicItemEntity { Id = bomMaintainTechnicItem.Id });
                if (bomTechnicItem == null)
                    return 3;
                if (BomTechnicItemBs.DeleteBomTechnicItem(bomTechnicItem))
                    return null;
                else return -1;
            }
            catch (Exception ex)
            {
                throw new FaultException<ProcessExecutionFault>
                    (new ProcessExecutionFault(), ex.Message);
            }
        }

        public int? DelBomTechnicItems(List<BomMaintainTechnicItem> bomMaintainTechnicItems)
        {
            try
            {
                if (bomMaintainTechnicItems == null)
                    return 1;
                if (bomMaintainTechnicItems.Count == 0)
                    return 2;
                var tis = new List<BomTechnicItemEntity>();
                foreach (var mti in bomMaintainTechnicItems)
                {
                    var ti = BomTechnicItemBs.GetBomTechnicItem(new BomTechnicItemEntity { Id = mti.Id });
                    tis.Add(ti);
                }
                if (BomTechnicItemBs.DeleteBomTechnicItem(tis))
                    return null;
                else return -1;
            }
            catch (Exception ex)
            {
                throw new FaultException<ProcessExecutionFault>
                    (new ProcessExecutionFault(), ex.Message);
            }
        }

        public List<BomMaintainTechnicItem> GetBomTechnicItem(string bomTechnicId)
        {
            if (string.IsNullOrEmpty(bomTechnicId))
                return null;
            DataSet ds = BomTechnicItemBs.GetBomTechnicItemAllDsByTechId(bomTechnicId);

            var results = new List<BomMaintainTechnicItem>();
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                var result = new BomMaintainTechnicItem
                {
                    Id = dr["ID"].ToString(),
                    BomTechnicId = dr["BOM_TECHNIC_ID"].ToString(),
                    TechnicId = dr["TECHNIC_ID"].ToString(),
                    TechnicName = dr["TECHNIC_NAME"].ToString(),
                    Sequence = (int)dr["SEQUENCE"],
                    Description = dr["DESCRIPTION"].ToString(),
                    TechnicCode = dr["TECHNIC_CODE"].ToString(),
                    EqptType = dr["EQPT_TYPE"].ToString(),
                    CloseTime = string.IsNullOrEmpty(dr["CLOSE_TIME"].ToString()) ? 0 : Convert.ToDecimal(dr["CLOSE_TIME"]),
                    RateTime = string.IsNullOrEmpty(dr["RATE_TIME"].ToString()) ? 0 : Convert.ToDecimal(dr["RATE_TIME"]),
                    ReadyTime = string.IsNullOrEmpty(dr["READY_TIME"].ToString()) ? 0 : Convert.ToDecimal(dr["READY_TIME"]),
                    StationType = dr["STATION_TYPE"].ToString(),
                    BaseQty = Convert.ToInt32(dr["BASE_QTY"])
                };
                results.Add(result);
            }
            return results;
        }

        public DataSet GetBomTechnicItemAllDsByTechnicId(string bomTechnicId)
        {
            if (string.IsNullOrEmpty(bomTechnicId))
                return null;
            string sql = @"select bi.*,t.TECHNIC_NAME 
from BOM_TECHNIC_ITEM bi
left join PROD_TECHNIC t on bi.TECHNIC_ID=t.TECHNIC_ID
where bi.BOM_TECHNIC_ID='{0}' order by bi.SEQUENCE";
            sql = string.Format(sql, bomTechnicId);
            return BomTechnicBs.GetAllDsBySql(sql);

        }

        public int? SaveBomTechnicItem(List<BomMaintainTechnicItem> bomMaintainTechnicItems)
        {
            if (bomMaintainTechnicItems == null)
                return 1;
            if (bomMaintainTechnicItems.Count == 0)
                return 2;
            var curBtis = BomTechnicItemBs.GetListBomTechnicItemAllListByTechId(bomMaintainTechnicItems[0].BomTechnicId);
            List<BomTechnicItemEntity> newBtis = new List<BomTechnicItemEntity>();
            List<BomTechnicItemEntity> updateBtis = new List<BomTechnicItemEntity>();
            List<BomTechnicItemEntity> delBtis = new List<BomTechnicItemEntity>();
            if (curBtis == null || curBtis.Count == 0)
            {
                foreach (var mti in bomMaintainTechnicItems)
                {
                    var ti = new BomTechnicItemEntity();
                    ti.Id = mti.Id;
                    ti.Sequence = mti.Sequence;
                    ti.BomTechnicId = mti.BomTechnicId;
                    ti.TechnicId = mti.TechnicId;
                    ti.Description = mti.Description;
                    ti.TechnicCode = mti.TechnicCode;
                    ti.TechnicName = mti.TechnicName;
                    ti.StationType = mti.StationType;
                    ti.RateTime = mti.RateTime;
                    ti.ReadyTime = mti.ReadyTime;
                    ti.CloseTime = mti.CloseTime;
                    ti.BaseQty = mti.BaseQty;
                    newBtis.Add(ti);
                }
                if (BomTechnicItemBs.InsertBomTechnicItem(newBtis))
                    return null;
                else return -1;
            }
            else
            {
                //foreach (var mti in bomMaintainTechnicItems)
                //{
                //    var bti = curBtis.Find(a => a.Id == mti.Id);
                //    if (bti != null)//更新
                //    {
                //        bti.TechnicId = mti.TechnicId;
                //        bti.BomTechnicId = mti.BomTechnicId;
                //        bti.Sequence = mti.Sequence;
                //        bti.Description = mti.Description;
                //        updateBtis.Add(bti);
                //        curBtis.Remove(bti);
                //    }
                //    else
                //    {
                //        var ti = new BomTechnicItemEntity();
                //        ti.Id = mti.Id;
                //        ti.TechnicId = mti.TechnicId;
                //        ti.BomTechnicId = mti.BomTechnicId;
                //        ti.Sequence = mti.Sequence;
                //        ti.Description = mti.Description;
                //        newBtis.Add(ti);
                //    }
                //}
                string bomTechnicId = "";

                foreach (var mti in bomMaintainTechnicItems)
                {
                    if (!bomTechnicId.Equals(mti.BomTechnicId))
                    {
                        bomTechnicId = mti.BomTechnicId;
                        curBtis = BomTechnicItemBs.GetListBomTechnicItemAllListByTechId(bomTechnicId);
                        if (curBtis != null && curBtis.Count > 0)
                        {
                            delBtis.AddRange(curBtis);
                        }
                        Console.WriteLine(bomTechnicId);
                    }
                    var ti = new BomTechnicItemEntity();
                    ti.Id = mti.Id;
                    ti.Sequence = mti.Sequence;
                    ti.BomTechnicId = mti.BomTechnicId;
                    ti.TechnicId = mti.TechnicId;
                    ti.Description = mti.Description;
                    ti.TechnicCode = mti.TechnicCode;
                    ti.TechnicName = mti.TechnicName;
                    ti.StationType = mti.StationType;
                    ti.RateTime = mti.RateTime;
                    ti.ReadyTime = mti.ReadyTime;
                    ti.CloseTime = mti.CloseTime;
                    ti.BaseQty = mti.BaseQty;
                    newBtis.Add(ti);
                }

                if (BomTechnicItemBs.Save(newBtis, updateBtis, delBtis))
                    return null;
                else return -1;
            }
        }


        //bom签核完成动作.  成功 return "",否则 返回失败信息
        public string BptBomWfEnd(BomMaintainMaster bomMaster)
        {
            try
            {
                if (bomMaster == null)
                    return "没指定bom实体";
                BomMasterEntity bom = DataAccess.SelectSingle<BomMasterEntity>(new BomMasterEntity { Id = bomMaster.Id });
                if (bom == null) return "没有找到bom实体" + bomMaster.Id;
                bom.Status = Common.WfStatus.WFS30.ToString();
                bom.IsActive = 1;
                if (!DataAccess.Update(bom))
                {
                    return "实体状态更新失败";
                }
                else
                {
                    return null;
                }
            }
            catch (Exception ex)
            {
                MyDebug.write("BptBomWfEnd:" + ex.Message);
                return ex.Message;
            }

        }


        public List<BomTechnicEntity> BptBomToTechnic(BomMaintainMaster bomMaster, string userNo)
        {
            if (bomMaster == null || string.IsNullOrEmpty(userNo))
                return null;
            var bomMasters = BomMasterBs.GetBomMasterAllListByProductId(bomMaster.ProductId);
            if (bomMasters == null)
                return null;
            if (bomMaster.IsActive == 1)
            {
                foreach (var b in bomMasters)
                {
                    //同一产品只有一个bom是生效状态
                    if (!b.Id.Equals(bomMaster.Id))
                    {
                        b.IsActive = 0;
                    }
                    else
                    {
                        b.Status = Common.WfStatus.WFS30.ToString();
                    }
                }
                if (!BomMasterBs.UpdateBomMaster(bomMasters))
                    return null;
            }
            var bomItems = BomItemBs.GetListBomItemByMasterId(bomMaster.Id);
            var bts = new List<BomTechnicEntity>();
            var bt = new BomTechnicEntity();
            bt.Id = Guid.NewGuid().ToString();
            bt.CreatedBy = userNo;
            bt.CreatedDate = DateTime.Now;
            bt.UpdatedBy = userNo;
            bt.UpdatedDate = DateTime.Now;
            bt.IsActive = 1;
            bt.ProductId = bomMaster.ProductId;
            bt.Ver = DateTime.Now.ToString("yyyyMMddHHmmss");
            bt.Description = "系统自动产生";
            bt.Status = Common.WfStatus.WFS10.ToString();
            bts.Add(bt);
            if (bomItems != null && bomItems.Count != 0)
            {
                foreach (var bi in bomItems)
                {
                    if (!bi.ItemType.Equals("PDTYPE01") && !bi.ItemType.Equals("PDTYPE04"))
                        continue;
                    bt = new BomTechnicEntity();
                    bt.Id = Guid.NewGuid().ToString();


                    bt.CreatedBy = userNo;
                    bt.CreatedDate = DateTime.Now;
                    bt.UpdatedBy = userNo;
                    bt.UpdatedDate = DateTime.Now;
                    bt.IsActive = 0;
                    bt.ProductId = bi.ProductId;
                    bt.Ver = DateTime.Now.ToString("yyyyMMddHHmmss");
                    bt.Description = "系统自动产生";
                    bt.Status = Common.WfStatus.WFS10.ToString();
                    bts.Add(bt);
                }
            }
            if (BomTechnicBs.InsertBomTechnic(bts))
                return bts;
            else return null;
        }

        public BomMasterEntity GetBomByKey(string bomId)
        {
            try
            {
                if (string.IsNullOrEmpty(bomId))
                    return null;
                return BomMasterBs.GetBomMaster(new BomMasterEntity { Id = bomId });
            }
            catch (Exception ex)
            {
                throw new FaultException<ProcessExecutionFault>
                    (new ProcessExecutionFault(), ex.Message);
            }
        }

        public BomMaintainMaster GetBomMasterByKey(string bomMasterId)
        {
            if (string.IsNullOrEmpty(bomMasterId))
                return null;
            var bm = BomMasterBs.GetBomMaster(new BomMasterEntity { Id = bomMasterId });
            if (bm == null)
                return null;
            string connectionString = MyConfig.getConnection("myconstring");
            PowerService ps = new PowerService(new BPM.Foundation.PWDB.PWDBDataContext(connectionString));
            var bmm = new BomMaintainMaster();
            bmm.Id = bm.Id;
            var createdUser = ps.getUser(null, bm.CreatedBy);
            var updatedUser = ps.getUser(null, bm.UpdatedBy);
            if (createdUser != null)
            {
                bmm.CreatedBy = createdUser.userNo;
                bmm.CreatedUser = createdUser.firstName;
            }
            bmm.CreatedDate = DateTime.Now;
            if (updatedUser != null)
            {
                bmm.UpdatedBy = updatedUser.userNo;
                bmm.UpdatedUser = updatedUser.firstName;
            }
            bmm.UpdatedDate = DateTime.Now;
            bmm.IsActive = 1;
            bmm.BlueprintId = bm.BlueprintId;
            var product = MstProductBs.GetMstProduct(new MstProductEntity { ProductId = bm.ProductId });
            if (product != null)
            {
                bmm.ProductId = product.ProductId;
                bmm.ProductName = product.ProductName;
                bmm.ProductCode = product.ProductCode;
            }
            bmm.Name = bm.Name;
            bmm.Description = bm.Description;
            bmm.Ver = bm.Ver;
            bmm.Status = bm.Status;
            return bmm;

        }

        public List<BomMaintainMaster> GetBomMasterAllListByProductId(string productId)
        {
            if (string.IsNullOrEmpty(productId))
                return null;
            var bms = BomMasterBs.GetBomMasterActiveAllListByProductId(productId);
            if (bms == null)
                return null;
            string connectionString = MyConfig.getConnection("myconstring");
            PowerService ps = new PowerService(new BPM.Foundation.PWDB.PWDBDataContext(connectionString));
            var bmms = new List<BomMaintainMaster>();
            foreach (var bm in bms)
            {
                var bmm = new BomMaintainMaster();
                bmm.Id = bm.Id;
                var createdUser = ps.getUser(null, bm.CreatedBy);
                var updatedUser = ps.getUser(null, bm.UpdatedBy);
                if (createdUser != null)
                {
                    bmm.CreatedBy = createdUser.userNo;
                    bmm.CreatedUser = createdUser.firstName;
                }
                bmm.CreatedDate = DateTime.Now;
                if (updatedUser != null)
                {
                    bmm.UpdatedBy = updatedUser.userNo;
                    bmm.UpdatedUser = updatedUser.firstName;
                }
                bmm.UpdatedDate = DateTime.Now;
                bmm.IsActive = 1;
                bmm.BlueprintId = bm.BlueprintId;
                var product = MstProductBs.GetMstProduct(new MstProductEntity { ProductId = bm.ProductId });
                if (product != null)
                {
                    bmm.ProductId = product.ProductId;
                    bmm.ProductName = product.ProductName;
                    bmm.ProductCode = product.ProductCode;
                }
                bmm.Name = bm.Name;
                bmm.Description = bm.Description;
                bmm.Ver = bm.Ver;
                bmm.Status = bm.Status;
                bmms.Add(bmm);
            }
            return bmms;

        }


        //获取所有bom列表
        public List<BomMaintainMaster> GetAllActiveBomMaster()
        {

            var bms = BomMasterBs.GetAllActiveBomMaster();
            if (bms == null)
                return null;
            string connectionString = MyConfig.getConnection("myconstring");
            PowerService ps = new PowerService(new BPM.Foundation.PWDB.PWDBDataContext(connectionString));
            var bmms = new List<BomMaintainMaster>();
            foreach (var bm in bms)
            {
                var bmm = new BomMaintainMaster();
                bmm.Id = bm.Id;
                var createdUser = ps.getUser(null, bm.CreatedBy);
                var updatedUser = ps.getUser(null, bm.UpdatedBy);
                if (createdUser != null)
                {
                    bmm.CreatedBy = createdUser.userNo;
                    bmm.CreatedUser = createdUser.firstName;
                }
                bmm.CreatedDate = DateTime.Now;
                if (updatedUser != null)
                {
                    bmm.UpdatedBy = updatedUser.userNo;
                    bmm.UpdatedUser = updatedUser.firstName;
                }
                bmm.UpdatedDate = DateTime.Now;
                bmm.IsActive = 1;
                bmm.BlueprintId = bm.BlueprintId;
                var product = MstProductBs.GetMstProduct(new MstProductEntity { ProductId = bm.ProductId });
                if (product != null)
                {
                    bmm.ProductId = product.ProductId;
                    bmm.ProductName = product.ProductName;
                    bmm.ProductCode = product.ProductCode;
                }
                bmm.Name = bm.Name;
                bmm.Description = bm.Description;
                bmm.Ver = bm.Ver;
                bmm.Status = bm.Status;
                bmms.Add(bmm);
            }
            return bmms;

        }

        public DataSet GetBomAllDsByCondition(BomQueryCondition queryCondition)
        {
            int pageIndex = 1;
            int pageCount = 50;
            if (queryCondition.txtPageIndex != 0)
                pageIndex = queryCondition.txtPageIndex;
            if (queryCondition.txtPageSize != 0)
                pageCount = queryCondition.txtPageSize;
            string condition = "";
            //if (queryCondition.IsActive != -1)
            //{
            //    condition += " and bm.is_active='" + queryCondition.IsActive + "'";
            //}
            if (!string.IsNullOrEmpty(queryCondition.Name))
            {
                condition += " and bm.name like '%" + queryCondition.Name + "%'";
            }
            if (!string.IsNullOrEmpty(queryCondition.ProductId))
            {
                condition += " and bm.product_id='" + queryCondition.ProductId + "'";
            }
            else if (!string.IsNullOrEmpty(queryCondition.ProductName))
            {
                condition += " and p.product_name like '%" + queryCondition.ProductName + "%'";
            }
            if (!string.IsNullOrEmpty(queryCondition.Ver))
            {
                condition += " and bm.ver='" + queryCondition.Ver + "'";
            }
            if (!string.IsNullOrEmpty(queryCondition.Status))
            {
                condition += " and bm.status='" + queryCondition.Status + "'";
            }
            return BomMasterBs.GetAllDsByCondition(pageIndex, pageCount, condition);
        }

        public DataSet GetBomItemByMasterId(string bomMasterId)
        {
            if (string.IsNullOrEmpty(bomMasterId))
                return null;
            return BomItemBs.GetBomItemByMasterId(bomMasterId);
        }

        public BomMaintainMaster AddBomMaster(BomMaintainMaster bomMaintainMaster)
        {
            if (bomMaintainMaster == null)
                return null;
            var bm = new BomMasterEntity();
            bm.Id = bomMaintainMaster.Id;
            bm.CreatedBy = bomMaintainMaster.CreatedBy;
            bm.CreatedDate = DateTime.Now;
            bm.UpdatedBy = bomMaintainMaster.UpdatedBy;
            bm.UpdatedDate = DateTime.Now;
            bm.IsActive = bomMaintainMaster.IsActive;
            bm.Name = bomMaintainMaster.Name;
            bm.BlueprintId = bomMaintainMaster.BlueprintId;
            bm.ProductId = bomMaintainMaster.ProductId;
            bm.Description = bomMaintainMaster.Description;
            bm.Ver = bomMaintainMaster.Ver;
            bm.Status = bomMaintainMaster.Status;

            bomMaintainMaster.CreatedDate = DateTime.Now;
            bomMaintainMaster.UpdatedDate = DateTime.Now;
            if (BomMasterBs.InsertBomMaster(bm))
                return bomMaintainMaster;
            else return null;

        }

        public BomMaintainMaster UpdateBomMaster(BomMaintainMaster bomMaintainMaster)
        {
            if (bomMaintainMaster == null)
                return null;
            BomMasterEntity bm = BomMasterBs.GetBomMaster(new BomMasterEntity { Id = bomMaintainMaster.Id });
            if (bm == null)
                return null;
            bm.UpdatedBy = bomMaintainMaster.UpdatedBy;
            bm.UpdatedDate = DateTime.Now;
            bm.IsActive = bomMaintainMaster.IsActive;
            bm.Name = bomMaintainMaster.Name;
            bm.BlueprintId = bomMaintainMaster.BlueprintId;
            bm.ProductId = bomMaintainMaster.ProductId;
            bm.Description = bomMaintainMaster.Description;
            bm.Ver = bomMaintainMaster.Ver;
            bm.Status = bomMaintainMaster.Status;

            bomMaintainMaster.UpdatedDate = DateTime.Now;
            if (BomMasterBs.UpdateBomMaster(bm))
                return bomMaintainMaster;
            else return null;
        }
        
        public bool DelBomMaster(BomMaintainMaster bomMaintainMaster)
        {
            if (bomMaintainMaster == null)
                return false;
            var bm = BomMasterBs.GetBomMaster(new BomMasterEntity { Id = bomMaintainMaster.Id });
            if (bm == null)
                return false;
            return BomMasterBs.DelBomMaster(bm);
        }

        public bool SaveBomItem(DataSet bomItems, DataSet delItems)
        {
            if (bomItems == null)
                return false;
            if (bomItems.Tables[0].Rows.Count == 0)
                return false;

            List<BomItemEntity> insertList = new List<BomItemEntity>();
            //List<BomItemEntity> modifyList = new List<BomItemEntity>();
            List<BomItemEntity> delList = new List<BomItemEntity>();
            foreach (DataRow dr in bomItems.Tables[0].Rows)
            {
                //BomItemEntity entity = null;
                //switch (dr.RowState)
                //{
                //    case DataRowState.Added:
                //        entity = new BomItemEntity(dr);
                //        insertList.Add(entity);
                //        break;
                //    case DataRowState.Modified:
                //        entity = new BomItemEntity(dr);
                //        modifyList.Add(entity);
                //        break;
                //    default:
                //        continue;
                //}
                BomItemEntity entity = new BomItemEntity(dr);
                insertList.Add(entity);
            }

            if (delItems != null && delItems.Tables.Count != 0 && delItems.Tables[0].Rows.Count != 0)
            {
                foreach (DataRow dr in delItems.Tables[0].Rows)
                {
                    var del = new BomItemEntity(dr);
                    delList.Add(del);
                }
            }
            //return BomItemBs.SaveBomItem(insertList, modifyList, delList);
            return BomItemBs.SaveBomItem(insertList);
        }

        /// <summary>
        /// 根据产品查询其物料清单（不包含自身）
        /// </summary>
        /// <param name="productId"></param>
        /// <returns></returns>
        public DataSet GetDsBomItemByParentBom(BomMaintainMaster bm)
        {

            DataSet ds = new DataSet();
            ds.Tables.Add();
            ds.Tables[0].Columns.Add("ID");
            ds.Tables[0].Columns.Add("BOM_MASTER_ID");
            ds.Tables[0].Columns.Add("PARENT_ID");
            ds.Tables[0].Columns.Add("VERSION");
            ds.Tables[0].Columns.Add("PRODUCT_ID");
            ds.Tables[0].Columns.Add("ITEM_TYPE");
            ds.Tables[0].Columns.Add("SEQENCE", typeof(int));
            ds.Tables[0].Columns.Add("UNIT_DOSE", typeof(decimal));
            ds.Tables[0].Columns.Add("LOSS_RATE", typeof(decimal));
            ds.Tables[0].Columns.Add("CONSTANT_SCRAP", typeof(decimal));
            ds.Tables[0].Columns.Add("EFFECTIVE_DATE", typeof(DateTime));
            ds.Tables[0].Columns.Add("EXPIRATION_DATE", typeof(DateTime));
            ds.Tables[0].Columns.Add("PICKING_PRODUCT_TECHNIC_ID");
            ds.Tables[0].Columns.Add("IS_CUSTOMER_FOR", typeof(int));
            ds.Tables[0].Columns.Add("SUPPLIER_ID");
            ds.Tables[0].Columns.Add("START_LOTS");
            ds.Tables[0].Columns.Add("END_LOTS");
            ds.Tables[0].Columns.Add("REMARK");
            ds.Tables[0].Columns.Add("PRODUCT_NAME");
            ds.Tables[0].Columns.Add("PRODUCT_CODE");

            ds.Tables[0].Columns.Add("MTRL_ID");
            ds.Tables[0].Columns.Add("PICKING_MODEL");
            ds.Tables[0].Columns.Add("NET_SIZE");
            ds.Tables[0].Columns.Add("GROSS_SIZE");
            ds.Tables[0].Columns.Add("UNIT_WEIGHT", typeof(decimal));
            ds.Tables[0].Columns.Add("MANUFACTURING_TYPE");
            ds.Tables[0].Columns.Add("LOGIC_NO");
            ds.Tables[0].Columns.Add("BP_ID");
            ds.Tables[0].Columns.Add("UNIT");
            BptBlueprintEntity bb = BptBlueprintBs.GetBptBlueprint(new BptBlueprintEntity { ProductId = bm.ProductId, DeletefLag = 0 });
            if (bb == null)
                return ds;
            List<BptBlueprintEntity> bbs = BptBlueprintBs.getBptBpsByParentID(bb.BlueprintId);
            if (bbs == null)
                return ds;
            int seq = 1;
            foreach (var b in bbs)
            {
                var dr = ds.Tables[0].NewRow();
                dr["ID"] = Guid.NewGuid().ToString();
                dr["BOM_MASTER_ID"] = bm.Id;
                dr["VERSION"] = "1.0";
                dr["PRODUCT_ID"] = b.ProductId;
                var product = MstProductBs.GetMstProduct(new MstProductEntity { ProductId = b.ProductId });
                if (product != null)
                {
                    dr["PRODUCT_NAME"] = product.ProductName;
                    dr["PRODUCT_CODE"] = product.ProductCode;
                }
                //dr["ITEM_TYPE"] = "";
                dr["SEQENCE"] = seq++;
                dr["UNIT_DOSE"] = b.MaterialQty;
                dr["UNIT"] = product.Unit;
                dr["ITEM_TYPE"] = "PDTYPE01";
                //dr["LOSS_RATE"] = "";
                //dr["CONSTANT_SCRAP"] = "";
                //dr["EFFECTIVE_DATE"] = "";
                //dr["PICKING_PRODUCT_TECHNIC_ID"] = "";
                //dr["IS_CUSTOMER_FOR"] = "";
                //dr["SUPPLIER_ID"] = "";
                //dr["START_LOTS"] = "";
                //dr["END_LOTS"] = "";
                //dr["REMARK"] = "";

                ds.Tables[0].Rows.Add(dr);
            }
            return ds;

        }

        public List<BomMaintainTechnicItem> GetBomMTIAllListByProductId(string productId)
        {
            var bomTechnic = BomTechnicBs.GetBomTechnic(new BomTechnicEntity { ProductId = productId, IsActive = 1, Status = Common.WfStatus.WFS30.ToString() });
            if (bomTechnic == null)
                return null;
            DataSet ds = BomTechnicItemBs.GetBomTechnicItemAllDsByTechId(bomTechnic.Id);
            if (ds.Tables[0].Rows.Count == 0)
                return null;
            var results = new List<BomMaintainTechnicItem>();
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                var result = new BomMaintainTechnicItem
                {
                    Id = dr["ID"].ToString(),
                    BomTechnicId = dr["BOM_TECHNIC_ID"].ToString(),
                    TechnicId = dr["TECHNIC_ID"].ToString(),
                    TechnicName = dr["TECHNIC_NAME"].ToString(),
                    Sequence = (int)dr["SEQUENCE"],
                    Description = dr["DESCRIPTION"].ToString()
                };
                results.Add(result);
            }
            return results;
        }

        public DataSet GetBomAllDsByMasterId(string bomMasterId)
        {
            if (string.IsNullOrEmpty(bomMasterId))
                return null;
            var bomItems = BomItemBs.GetBomItemByMasterId(bomMasterId);
            var bomMaster = BomMasterBs.GetBomMaster(new BomMasterEntity { Id = bomMasterId });
            if (bomMaster == null)
                return null;


            //添加根结点

            bool rootExist = false;
            foreach (DataRow item in bomItems.Tables[0].Rows)
            {
                if (string.IsNullOrEmpty(item["PARENT_ID"].ToString()) && item["MTRL_ID"].ToString().Equals(item["PRODUCT_ID"].ToString()))
                    rootExist = true;
                if (string.IsNullOrEmpty(item["PARENT_ID"].ToString()) && !item["MTRL_ID"].ToString().Equals(item["PRODUCT_ID"].ToString()))
                {
                    item["PARENT_ID"] = bomMaster.Id;
                }
            }
            if (!rootExist)
            {
                DataRow dr = bomItems.Tables[0].NewRow();
                dr["ID"] = Guid.NewGuid().ToString();
                dr["BOM_MASTER_ID"] = bomMasterId;
                dr["PRODUCT_ID"] = bomMaster.ProductId;
                dr["UNIT_DOSE"] = 1;
                dr["ITEM_TYPE"] = "PDTYPE01";
                dr["VERSION"] = "1.0";
                var product = MstProductBs.GetMstProduct(new MstProductEntity { ProductId = bomMaster.ProductId });
                if (product == null)
                    return null;
                dr["PRODUCT_NAME"] = product.ProductName;
                dr["PRODUCT_CODE"] = product.ProductCode;
                if (string.IsNullOrEmpty(dr["UNIT"].ToString())) dr["UNIT"] = product.Unit;
                dr["MTRL_ID"] = bomMaster.ProductId;
                bomItems.Tables[0].Rows.Add(dr);
            }
            return bomItems;
        }

        public DTOString GetBomMaxVersion(string productId)
        {
            DTOString output = new DTOString();
            try
            {
                output.result = BomMasterBs.GetBomMaxVersion(productId);
            }
            catch (Exception ex)
            {
                output.result = null;
                output.ErrorCode = "GetBomMaxVersion";
                output.ErrorMessage = ex.Message;
            }
            return output;
        }
        
        public BptBlueprintEntity GetBlueprintByKey(string id)
        {
            if (string.IsNullOrEmpty(id))
                return null;
            return BptBlueprintBs.GetBptBlueprint(new BptBlueprintEntity { BlueprintId = id });
        }
        
        //获取指定产品的图纸列表
        public DataSet GetBlueprintByProductId(string productId)
        {
            if (string.IsNullOrEmpty(productId))
                return null;
            return BptBlueprintBs.GetBlueprintByProductId(productId);
        }


        //获取所有产品的图纸列表
        public DataSet GetAllProductBlueprint()
        {
            return BptBlueprintBs.GetAllProductBlueprint();
        }


        public DataSet GetProdTechnicAll()
        {
            return ProdTechnicBs.GetProdTechnicAll();
        }

        #region 工序/ 工艺路线
        public List<BomTechnicItemMtrlEntity> GetBomTechnicItemMtrlByTechnicId(string bomTechnicId)
        {
            return BomTechnicItemMtrlBs.GetBomTechnicItemMtrlByTechnicId(bomTechnicId);
        }

        public List<BomTechnicItemMtrlEntity> GetBomTechnicItemMtrlByTechnicItemId(string bomTechnicItemId)
        {
            return BomTechnicItemMtrlBs.GetBomTechnicItemMtrlByTechnicItemId(bomTechnicItemId);
        }


        public int? SaveBomTechnicItemMtrl(List<BomTechnicItemMtrlEntity> bomTechnicItemMtrls)
        {
            if (bomTechnicItemMtrls == null)
                return 1;
            if (bomTechnicItemMtrls.Count == 0)
                return 2;
            List<BomTechnicItemMtrlEntity> delsMtrls = new List<BomTechnicItemMtrlEntity>();
            string bomTechnicId = "";
            foreach (BomTechnicItemMtrlEntity m in bomTechnicItemMtrls)
            {
                if (bomTechnicId != m.BomTechnicId)
                {
                    List<BomTechnicItemMtrlEntity> dels = GetBomTechnicItemMtrlByTechnicId(m.BomTechnicId);
                    delsMtrls.AddRange(dels);
                }
                bomTechnicId = m.BomTechnicId;
            }

            List<BomTechnicItemMtrlEntity> updates = new List<BomTechnicItemMtrlEntity>();
            if (BomTechnicItemMtrlBs.Save(bomTechnicItemMtrls, updates, delsMtrls))
                return null;
            else return -1;

        }


        public int? DeleteBomTechnicAndDetail(BomMaintainTechnic bomMaintainTechnic)
        {
            try
            {
                if (bomMaintainTechnic == null)
                    return 1;
                if (string.IsNullOrEmpty(bomMaintainTechnic.Id))
                    return 2;
                BomTechnicEntity bomTechnic = BomTechnicBs.GetBomTechnic(new BomTechnicEntity { Id = bomMaintainTechnic.Id });
                if (bomTechnic == null)
                    return 3;
                if (BomTechnicBs.DeleteBomTechnicAndDetail(bomTechnic))
                    return null;
                else return -1;
            }
            catch (Exception ex)
            {
                throw new FaultException<ProcessExecutionFault>
                    (new ProcessExecutionFault(), ex.Message);
            }
        }


        public List<BptBlueprintEntity> GetBlueprintAllListByTaskId(string taskId)
        {
            if (string.IsNullOrEmpty(taskId))
                return null;
            return DataAccess.Select<BptBlueprintEntity>(new BptBlueprintEntity { BptTaskId = taskId });
        }


        public List<BomMaintainTechnic> AddBomTechnicList(List<BomMaintainTechnic> bomMaintainTechnicList)
        {
            try
            {
                if (bomMaintainTechnicList == null)
                    return null;
                List<BomTechnicEntity> technics = new List<BomTechnicEntity>();
                string connectionString = MyConfig.getConnection("myconstring");
                PowerService ps = new PowerService(new BPM.Foundation.PWDB.PWDBDataContext(connectionString));
                foreach (BomMaintainTechnic bomMaintainTechnic in bomMaintainTechnicList)
                {
                    bomMaintainTechnic.CreatedDate = DateTime.Now;
                    bomMaintainTechnic.UpdatedDate = DateTime.Now;

                    var createdUser = ps.getUser(null, bomMaintainTechnic.CreatedBy);
                    if (createdUser != null && !string.IsNullOrEmpty(createdUser.firstName))
                        bomMaintainTechnic.CreatedUser = createdUser.firstName;
                    var updatedUser = ps.getUser(null, bomMaintainTechnic.UpdatedBy);
                    if (updatedUser != null && !string.IsNullOrEmpty(updatedUser.firstName))
                        bomMaintainTechnic.UpdatedUser = updatedUser.firstName;
                    BomTechnicEntity bomTechnic = new BomTechnicEntity
                    {
                        Id = bomMaintainTechnic.Id,
                        CreatedBy = bomMaintainTechnic.CreatedBy,
                        CreatedDate = bomMaintainTechnic.CreatedDate,
                        UpdatedBy = bomMaintainTechnic.UpdatedBy,
                        UpdatedDate = bomMaintainTechnic.UpdatedDate,
                        IsActive = bomMaintainTechnic.IsActive,
                        ProductId = bomMaintainTechnic.ProductId,
                        ProductName = bomMaintainTechnic.ProductName,
                        ProductCode = bomMaintainTechnic.ProductCode,
                        Ver = bomMaintainTechnic.Ver,
                        Description = bomMaintainTechnic.Description,
                        Status = bomMaintainTechnic.Status,
                        ParentId = bomMaintainTechnic.ParentId,
                        LogicNo = bomMaintainTechnic.LogicNo,
                        Name = bomMaintainTechnic.Name
                    };
                    technics.Add(bomTechnic);
                }
                if (BomTechnicBs.InsertBomTechnic(technics))
                    return bomMaintainTechnicList;
                else return null;
            }
            catch (Exception ex)
            {
                throw new FaultException<ProcessExecutionFault>
                    (new ProcessExecutionFault(), ex.Message);
            }
        }

        public List<BomMaintainTechnic> UpdateBomTechnicList(List<BomMaintainTechnic> bomMaintainTechnicList)
        {
            try
            {
                if (bomMaintainTechnicList == null)
                    return null;
                if (bomMaintainTechnicList.Count == 0)
                    return null;
                List<BomTechnicEntity> technics = new List<BomTechnicEntity>();

                foreach (BomMaintainTechnic bomMaintainTechnic in bomMaintainTechnicList)
                {
                    // BomTechnicEntity bomTechnic = BomTechnicBs.GetBomTechnic(new BomTechnicEntity { Id = bomMaintainTechnic.Id });
                    // if (bomTechnic == null)
                    //    return null;
                    BomTechnicEntity bomTechnic = new BomTechnicEntity();
                    bomTechnic.Id = bomMaintainTechnic.Id;
                    bomTechnic.CreatedBy = bomMaintainTechnic.CreatedBy;
                    bomTechnic.CreatedDate = bomMaintainTechnic.CreatedDate;
                    bomTechnic.UpdatedDate = DateTime.Now;

                    bomTechnic.UpdatedBy = bomMaintainTechnic.UpdatedBy;
                    bomTechnic.UpdatedDate = bomMaintainTechnic.UpdatedDate;
                    bomTechnic.IsActive = bomMaintainTechnic.IsActive;
                    bomTechnic.ProductId = bomMaintainTechnic.ProductId;
                    bomTechnic.ProductName = bomMaintainTechnic.ProductName;
                    bomTechnic.ProductCode = bomMaintainTechnic.ProductCode;
                    bomTechnic.Ver = bomMaintainTechnic.Ver;
                    bomTechnic.Description = bomMaintainTechnic.Description;
                    bomTechnic.Status = bomMaintainTechnic.Status;
                    bomTechnic.ParentId = bomMaintainTechnic.ParentId;
                    bomTechnic.LogicNo = bomMaintainTechnic.LogicNo;
                    bomTechnic.Name = bomMaintainTechnic.Name;
                    technics.Add(bomTechnic);
                    // bool result = false;
                    //if (bomTechnic.IsActive == 1)
                    //    result = BomTechnicBs.UpdateAndActiveBomTechnic(bomTechnic);
                    //else
                    //    result = BomTechnicBs.UpdateBomTechnic(bomTechnic);
                }
                if (BomTechnicBs.UpdateBomTechnicWithTransaction(technics))
                    return bomMaintainTechnicList;
                else return null;
            }
            catch (Exception ex)
            {
                throw new FaultException<ProcessExecutionFault>
                    (new ProcessExecutionFault(), ex.Message);
            }
        }


        public List<BomMaintainTechnic> GetBomTechnicByLogicNo(string LogicNo)
        {
            try
            {
                if (string.IsNullOrEmpty(LogicNo))
                    return null;
                var technics = BomTechnicBs.GetBomTechnicByLogicNo(LogicNo);
                if (technics == null)
                    return null;
                string connectionString = MyConfig.getConnection("myconstring");
                PowerService ps = new PowerService(new BPM.Foundation.PWDB.PWDBDataContext(connectionString));
                List<BomMaintainTechnic> maintainTechnics = new List<BomMaintainTechnic>();
                foreach (BomTechnicEntity bomT in technics)
                {
                    var createdUser = ps.getUser(null, bomT.CreatedBy);
                    var updatedUser = ps.getUser(null, bomT.UpdatedBy);
                    var product = MstProductBs.GetMstProduct(new MstProductEntity { ProductId = bomT.ProductId });
                    BomMaintainTechnic bomMT = new BomMaintainTechnic
                    {
                        Id = bomT.Id,
                        CreatedBy = bomT.CreatedBy,
                        CreatedUser = (createdUser != null) ? createdUser.firstName : "",
                        CreatedDate = DateTime.Now,
                        UpdatedBy = bomT.UpdatedBy,
                        UpdatedUser = (updatedUser != null) ? updatedUser.firstName : "",
                        UpdatedDate = DateTime.Now,
                        IsActive = bomT.IsActive,
                        ProductId = bomT.ProductId,
                        ProductCode = product.ProductCode,
                        ProductName = product.ProductName,
                        Ver = bomT.Ver,
                        Description = bomT.Description,
                        Status = bomT.Status,
                        ParentId = bomT.ParentId,
                        LogicNo = bomT.LogicNo,
                        Name = bomT.Name
                    };
                    maintainTechnics.Add(bomMT);
                }
                return maintainTechnics;
            }
            catch (Exception ex)
            {
                throw new FaultException<ProcessExecutionFault>
                    (new ProcessExecutionFault(), ex.Message);
            }
        }

        public BomMaintainTechnicItem GetBomTechnicItemByKey(string technicItemId)
        {
            try
            {
                if (string.IsNullOrEmpty(technicItemId))
                    return null;
                var technics = BomTechnicItemBs.GetBomTechnicItem(new BomTechnicItemEntity { Id = technicItemId });
                if (technics == null) return null;
                BomMaintainTechnicItem item = new BomMaintainTechnicItem();
                item.Id = technics.Id;
                item.BomTechnicId = technics.BomTechnicId;
                item.TechnicId = technics.TechnicId;
                item.TechnicName = technics.TechnicName;
                item.Sequence = technics.Sequence;
                item.Description = technics.Description;
                item.TechnicCode = technics.TechnicCode;
                item.EqptType = technics.EqptType;
                item.CloseTime = technics.CloseTime;
                item.RateTime = technics.RateTime;
                item.ReadyTime = technics.ReadyTime;
                item.StationType = technics.StationType;
                item.BaseQty = technics.BaseQty;
                return item;
            }
            catch (Exception ex)
            {
                throw new FaultException<ProcessExecutionFault>
                    (new ProcessExecutionFault(), ex.Message);
            }
        }

        public string AddProdTechnic(ProdTechnicEntity entity)
        {
            try
            {
                bool re = ProdTechnicBs.InsertProdTechnic(entity);
                if (re)
                    return "";
                else
                    return "添加失改！";

            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }


        public string UpdateProdTechnic(ProdTechnicEntity entity)
        {
            try
            {
                entity.UpdatedDate = DateTime.Now;
                bool re = ProdTechnicBs.UpdateProdTechnic(entity);
                if (re)
                    return "";
                else
                    return "修改失改！";

            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }


        public string DeleteProdTechnic(string id)
        {
            try
            {
                ProdTechnicEntity entity = ProdTechnicBs.GetProdTechnic(new ProdTechnicEntity { TechnicId = id });
                string checkRe = ProdTechnicBs.CheckProdTechnicUsed(entity);
                if (string.IsNullOrEmpty(checkRe))
                {
                    bool re = ProdTechnicBs.DeleteProdTechnic(entity);
                    if (re)
                        return "";
                    else
                        return "删除失改！";
                }
                else
                    return checkRe;

            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }


        public string CheckProdTechnicUsed(ProdTechnicEntity entity)
        {
            try
            {
                string checkRe = ProdTechnicBs.CheckProdTechnicUsed(entity);
                return checkRe;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        public ProdTechnicEntity GetProdTechnicByKey(string id)
        {
            return ProdTechnicBs.GetProdTechnic(new ProdTechnicEntity { TechnicId = id });
        }

        #endregion

        #region 图纸变更
        public DTODataTable GetBptBluePrintChangesByCondition(BptBlueprintChangesEntity condition)
        {

            DTODataTable output = new DTODataTable();
            try
            {
                output.result = BptBlueprintChangesBs.GetBptBluePrintChangesByCondition(condition);
            }
            catch (Exception ex)
            {
                output.result = null;
                output.ErrorCode = "GetBptBluePrintChangesByCondition";
                output.ErrorMessage = ex.Message;
            }
            return output;
        }



        public DTOBool DeleteBptBluePrintChanges(BptBlueprintChangesEntity entity)
        {
            DTOBool output = new DTOBool();
            try
            {
                output.result = BptBlueprintChangesBs.DeleteBptBlueprintChanges(entity);
            }
            catch (Exception ex)
            {
                output.result = false;
                output.ErrorCode = "DeleteBptBluePrintChanges";
                output.ErrorMessage = ex.Message;
            }
            return output;
        }

        public DTOBool InsertBptBluePrintChangesAndItems(BptBlueprintChangesEntity entity, List<BptBlueprintChangesItemEntity> items)
        {
            DTOBool output = new DTOBool();
            try
            {
                output.result = BptBlueprintChangesBs.InsertBptBlueprintChanges(entity, items);
            }
            catch (Exception ex)
            {
                output.result = false;
                output.ErrorCode = "InsertBptBluePrintChangesAndItems";
                output.ErrorMessage = ex.Message;
            }
            return output;
        }


        public DTOBool UpdateBptBluePrintChangesAndItems(BptBlueprintChangesEntity entity, List<BptBlueprintChangesItemEntity> items)
        {
            DTOBool output = new DTOBool();
            try
            {
                output.result = BptBlueprintChangesBs.UpdateBptBlueprintChanges(entity, items);
            }
            catch (Exception ex)
            {
                output.result = false;
                output.ErrorCode = "UpdateBptBluePrintChangesAndItems";
                output.ErrorMessage = ex.Message;
            }
            return output;
        }

        public DTOBool UpdateBptBluePrintChanges(BptBlueprintChangesEntity entity)
        {
            DTOBool output = new DTOBool();
            try
            {
                output.result = BptBlueprintChangesBs.UpdateBptBlueprintChanges(entity);
            }
            catch (Exception ex)
            {
                output.result = false;
                output.ErrorCode = "UpdateBptBluePrintChanges";
                output.ErrorMessage = ex.Message;
            }
            return output;
        }


        public DTODataTable GetBptBluePrintChangesItemsByCondition(BptBlueprintChangesEntity condition)
        {
            DTODataTable output = new DTODataTable();
            try
            {
                output.result = BptBlueprintChangesBs.GetBptBluePrintChangesItemsByCondition(condition);
            }
            catch (Exception ex)
            {
                output.result = null;
                output.ErrorCode = "GetBptBluePrintChangesByCondition";
                output.ErrorMessage = ex.Message;
            }
            return output;
        }


        public BptTaskEntity BptBlueprintChangeToTask(BptBlueprintChangesEntity bptMaintainApp, int days)
        {
            BptBlueprintChangesEntity bptApp = BptBlueprintChangesBs.GetBptBlueprintChanges(new BptBlueprintChangesEntity { Id = bptMaintainApp.Id });
            if (bptApp == null)
                return null;
            bptApp.Status = "BPTC03";
            bptApp.ReciveDate = bptMaintainApp.ReciveDate;
            bptApp.RecivePerson = bptMaintainApp.RecivePerson;
            if (!BptBlueprintChangesBs.UpdateBptBlueprintChanges(bptApp))
                return null;
            BptBlueprintChangesItemEntity items = DataAccess.SelectSingle<BptBlueprintChangesItemEntity>(new BptBlueprintChangesItemEntity { ChangesCode = bptApp.ChangesCode });
            BptTaskEntity bptTask = new BptTaskEntity();
            bptTask.Id = Guid.NewGuid().ToString();
            bptTask.BptAppId = bptApp.ChangesCode;
            bptTask.IsActive = 1;
            bptTask.CreatedBy = bptApp.CreatedBy;
            bptTask.CreatedDate = DateTime.Now;
            bptTask.UpdatedBy = bptApp.UpdatedBy;
            bptTask.UpdatedDate = DateTime.Now;
            string code = MstCodeRuleBs.GetCurrentOrderCode("BptTaskCode");
            if (code == null)
                return null;
            bptTask.TaskCode = code;
            bptTask.AssignUser = bptMaintainApp.RecivePerson;
            bptTask.RequiredDate = DateTime.Now.AddDays(days);
            if (items != null)
                bptTask.ProductId = items.ProductId;

            bptTask.Status = Common.WfStatus.WFS20.ToString();
            if (BptTaskBs.InsertBptTask(bptTask))
                return bptTask;
            else return null;
        }

        #endregion

        #region  技术申请
        public BptMaintainApp GetBptMaintainAppByCondition(BptMaintainApp bptAppEntity)
        {
            try
            {
                BptAppEntity bptApp = BptAppBs.GetBptApp(new BptAppEntity { Id = bptAppEntity.Id, AppCode = bptAppEntity.AppCode });
                if (bptApp == null)
                    return null;
                BptMaintainApp bptMaintainApp = new BptMaintainApp();
                bptMaintainApp.Id = bptApp.Id;
                bptMaintainApp.CreatedBy = bptApp.CreatedBy;
                string connectionString = MyConfig.getConnection("myconstring");
                PowerService ps = new PowerService(new BPM.Foundation.PWDB.PWDBDataContext(connectionString));
                var createdUser = ps.getUser(null, bptApp.CreatedBy);
                if (createdUser != null)
                    bptMaintainApp.CreatedUser = createdUser.firstName;
                bptMaintainApp.CreatedDate = bptApp.CreatedDate;
                bptMaintainApp.UpdatedBy = bptApp.UpdatedBy;
                var updatedUser = ps.getUser(null, bptApp.UpdatedBy);
                if (updatedUser != null)
                    bptMaintainApp.UpdatedUser = updatedUser.firstName;
                bptMaintainApp.UpdatedDate = bptApp.UpdatedDate;
                if (bptApp.SalesAppId != null)
                {
                    bptMaintainApp.SAppId = bptApp.SalesAppId;
                    var salesApp = DataAccess.SelectSingle<SalesAppEntity>(new SalesAppEntity { Id = bptApp.SalesAppId });
                    if (salesApp.AppNo != null)
                        bptMaintainApp.SAppOrderNo = salesApp.AppNo;
                }
                if (bptApp.SalesAppItemId != null)
                {
                    bptMaintainApp.SAppItemId = bptApp.SalesAppItemId;
                }
                if (bptApp.AppType != null)
                {
                    bptMaintainApp.AppType = bptApp.AppType;
                }
                if (bptApp.AppCode != null)
                {
                    bptMaintainApp.AppCode = bptApp.AppCode;
                }
                if (bptApp.RequiredDate != null)
                {
                    bptMaintainApp.RequiredDate = bptApp.RequiredDate;
                }
                if (bptApp.AssignUser != null)
                {
                    bptMaintainApp.AssignBy = bptApp.AssignUser;
                    var assignUser = ps.getUser(null, bptApp.AssignUser);
                    if (assignUser != null)
                        bptMaintainApp.AssignUser = assignUser.firstName;
                }
                if (bptApp.Description != null)
                {
                    bptMaintainApp.Description = bptApp.Description;
                }
                if (bptApp.Remark != null)
                {
                    bptMaintainApp.Remark = bptApp.Remark;
                }
                if (bptApp.FinishedDate != null)
                {
                    bptMaintainApp.FinshedDate = bptApp.FinishedDate;
                }
                if (bptApp.Material != null)
                {
                    bptMaintainApp.Material = bptApp.Material;
                }
                if (bptApp.ContractModel != null)
                {
                    bptMaintainApp.ContractModel = bptApp.ContractModel;
                }
                if (bptApp.Status != null)
                {
                    bptMaintainApp.Status = bptApp.Status;
                }
                return bptMaintainApp;
            }
            catch (Exception ex)
            {
                throw new FaultException<ProcessExecutionFault>
                    (new ProcessExecutionFault(), ex.Message);
            }
        }

        public BptMaintainTask GetBptMaintainTaskByCondition(BptMaintainTask bptTaskEntity)
        {
            try
            {

                var bptTask = BptTaskBs.GetBptTask(new BptTaskEntity { Id = bptTaskEntity.Id, TaskCode = bptTaskEntity.TaskCode });
                if (bptTask == null)
                    return null;
                BptMaintainTask bptMaintainTask = new BptMaintainTask();
                bptMaintainTask.Id = bptTask.Id;
                string connectionString = MyConfig.getConnection("myconstring");
                PowerService ps = new PowerService(new BPM.Foundation.PWDB.PWDBDataContext(connectionString));
                var createdUser = ps.getUser(null, bptTask.CreatedBy);
                if (createdUser != null)
                {
                    bptMaintainTask.CreatedUser = createdUser.userNo;
                    bptMaintainTask.CreatedBy = bptTask.CreatedBy;
                }
                bptMaintainTask.CreatedDate = bptTask.CreatedDate;
                var updatedUser = ps.getUser(null, bptTask.UpdatedBy);
                if (updatedUser != null)
                {
                    bptMaintainTask.UpdatedUser = updatedUser.userNo;
                    bptMaintainTask.UpdatedBy = bptTask.UpdatedBy;
                }
                bptMaintainTask.UploadDate = bptTask.UpdatedDate;
                if (string.IsNullOrEmpty(bptTask.BptAppId))
                    return null;
                if (!bptTask.BptAppId.StartsWith("BPTC"))
                {
                    #region 制图申请
                    var bptApp = BptAppBs.GetBptApp(new BptAppEntity { Id = bptTask.BptAppId });
                    if (bptApp != null)
                    {
                        bptMaintainTask.BAppId = bptApp.Id;
                        bptMaintainTask.BAppCode = bptApp.AppCode;
                    }
                    else
                    {
                        return null;
                    }
                    var salesApp = DataAccess.SelectSingle<SalesAppEntity>(new SalesAppEntity { Id = bptApp.SalesAppId });
                    if (salesApp != null)
                    {
                        bptMaintainTask.SAppId = salesApp.Id;
                        bptMaintainTask.SAppCode = salesApp.AppNo;
                    }
                    if (!string.IsNullOrEmpty(salesApp.CustomerId))
                    {
                        var customer = DataAccess.SelectSingle<MstCustomerEntity>(new MstCustomerEntity { Id = salesApp.CustomerId });
                        if (customer != null)
                        {
                            bptMaintainTask.CustomerName = customer.CustomerName;
                        }
                    }
                    bptMaintainTask.TaskCode = bptTask.TaskCode;
                    var assignUser = ps.getUser(null, bptTask.AssignUser);
                    if (assignUser != null)
                    {
                        bptMaintainTask.AssignBy = assignUser.userNo;
                        bptMaintainTask.AssignUser = assignUser.firstName;
                    }
                    bptMaintainTask.BlueprintId = bptTask.BlueprintId;
                    if (!string.IsNullOrEmpty(bptTask.ProductId))
                    {
                        var product = MstProductBs.GetMstProduct(new MstProductEntity { ProductId = bptTask.ProductId });
                        if (product != null)
                        {
                            bptMaintainTask.ProductId = product.ProductId;
                            bptMaintainTask.ProductName = product.ProductName;
                        }
                    }
                    #endregion
                }
                else
                {
                    #region 制图变更申请
                    var bptApp = BptBlueprintChangesBs.GetBptBlueprintChanges(new BptBlueprintChangesEntity { ChangesCode = bptTask.BptAppId });
                    if (bptApp != null)
                    {
                        bptMaintainTask.BAppId = bptApp.Id;
                        bptMaintainTask.BAppCode = bptApp.ChangesCode;
                    }
                    else
                    {
                        return null;
                    }
                    var salesApp = DataAccess.SelectSingle<BptBlueprintChangesItemEntity>(new BptBlueprintChangesItemEntity { ChangesCode = bptApp.ChangesCode });
                    if (salesApp != null)
                    {
                        bptMaintainTask.SAppId = salesApp.Id;
                        bptMaintainTask.SAppCode = salesApp.ChangesCode;
                    }
                    //if (!string.IsNullOrEmpty(salesApp.CustomerId))
                    //{
                    //    var customer = DataAccess.SelectSingle<MstCustomerEntity>(new MstCustomerEntity { Id = salesApp.CustomerId });
                    //    if (customer != null)
                    //    {
                    //        bptMaintainTask.CustomerName = customer.CustomerName;
                    //    }
                    //}
                    bptMaintainTask.TaskCode = bptTask.TaskCode;
                    var assignUser = ps.getUser(null, bptTask.AssignUser);
                    if (assignUser != null)
                    {
                        bptMaintainTask.AssignBy = assignUser.userNo;
                        bptMaintainTask.AssignUser = assignUser.firstName;
                    }
                    bptMaintainTask.BlueprintId = bptTask.BlueprintId;
                    if (!string.IsNullOrEmpty(bptTask.ProductId))
                    {
                        var product = MstProductBs.GetMstProduct(new MstProductEntity { ProductId = bptTask.ProductId });
                        if (product != null)
                        {
                            bptMaintainTask.ProductId = product.ProductId;
                            bptMaintainTask.ProductName = product.ProductName;
                        }
                    }
                    else
                    {
                        var list = DataAccess.Select<BptBlueprintChangesItemEntity>(new BptBlueprintChangesItemEntity { ChangesCode = bptApp.ChangesCode });
                        if (list != null && list.Count > 0)
                        {
                            bptMaintainTask.ProductId = list[0].ProductId;
                            var product = MstProductBs.GetMstProduct(new MstProductEntity { ProductId = bptMaintainTask.ProductId });
                            if (product != null)
                            {
                                bptMaintainTask.ProductName = product.ProductName;
                            }

                        }
                    }
                    #endregion
                }
                bptMaintainTask.WorkingTime = bptTask.WorkingTime;
                bptMaintainTask.RequiredDate = bptTask.RequiredDate;
                bptMaintainTask.UploadDate = bptTask.UploadDate;
                bptMaintainTask.FinishedDate = bptTask.FinishedDate;
                bptMaintainTask.Remark = bptTask.Remark;
                bptMaintainTask.Status = bptTask.Status;

                return bptMaintainTask;
            }
            catch (Exception ex)
            {
                throw new FaultException<ProcessExecutionFault>
                    (new ProcessExecutionFault(), ex.Message);
            }
        }
        #endregion


    }
}
